Reputation: 9183
I'm curious if these are zero initialized and all my pointers are 0 when I declare a fixed size array. I can say foo* arr[1000][1000]
and I see that all the entries are 0..but I am not sure if this is something I can rely on or not. I could say foo* arr[1000][1000] = {}
but this double array is a member variable in a class and I wouldn't want to have a double for loop in the constructor if it's not necessary...
Upvotes: 0
Views: 1252
Reputation: 75130
Depends on how you allocate the array.
If it's static
or global, then the contents will all be initialised to 0. If it's a local variable, then the contents won't be initialised to anything.
So since your array is a member variable, it won't be initialised to 0 automatically. However, you can initialise all the variables to zero by using the initialisation list in the constructor thusly:
struct A {
// VVV value-initialises the contents of arr
A() : arr() { }
double arr[x][y];
};
Upvotes: 4
Reputation: 208333
It depends on the context. If the array is defined at namespace level, then static initialization will set all pointers to null for you. If it is defined in a function scope or as a member of a class, there is no such guarantee.
Since it is a member of a class, it will not be correctly initialized, so you will need to initialize it manually. You can do so by adding arr()
to the initialization list. Being pointers, you can use memset
to set the whole array to 0 in a single call (which will also be as efficient as it gets), but beware, this only works for POD
types.
Upvotes: 3