I have a C class with a member that is supposed to be a two dimensional array. I want to declare my array as a member in the header file of the class. Then in the constructor of my class I want to initialize my array with a size (given to the constructor) and fill it with zeros.
I have a working example of what I want in java:
class Obj {
int[][] array;
public Obj(int sizex, int sizey) {
array = new int[sizex][sizey];
}
}
public class Main
{
public static void main(String[] args) {
Obj o = new Obj(12,20);
}
}
I do not want to mess with pointers or alloc() and free(). As my class is supposed to be basically a wrapper for this array, I want to keep it simple.
I have thought about using std::vector, but as the array is never being resized after its initialization, I feel like vector is a little overpowered... Is there a better way than this: ?
#include<vector>
class Obj {
std::vector<std::vector<int>> array;
public:
Obj(int xsize, int ysize) {
std::vector<std::vector<int>> newArray(xsize, std::vector<int>(ysize, 0));
array = newArray;
}
};
int main()
{
Obj o(12,20);
}
CodePudding user response:
std::vector
is the best match here. (As you said, in most cases raw arrays and pointers could be avoided. Also see How can I efficiently select a Standard Library container in C 11?)
And you can initialize array
directly in member initializer list instead of assigning in the constructor body after default-initialization, e.g.
Obj(int xsize, int ysize) : array(xsize, std::vector<int>(ysize, 0)) {
}
CodePudding user response:
Other than using std::vector you can just allocate memory of the required size from the heap.
class Obj {
int** arr;
int x, y;
public:
Obj(int sizex, int sizey) : x(sizex), y(sizey) {
arr = new int*[sizex];
for (unsigned i = 0; i < sizex; i ) {
arr[i] = new int[sizey];
}
}
//IMPORTANT TO DELETE, OTHERWISE YOU'LL GET A MEMORY LEAK
~Obj() {
for (unsigned i = 0; i < x; i ) {
delete[] arr[i];
}
delete[] arr;
}
}