I had trouble with initializing arrays of pointers. What I found out compiling with gcc c++ (4.6.0) is:
MyClass** a = new MyClass*[100];
Does not always initalize the array of pointers. (most of the time it did give me an array of null pointers which confused me)
MyClass** a = new MyClass*[100]();
DOES initialize all the pointers in the array to 0 (null pointer).
The code I'm writing is meant to be be portable across Windows/Linux/Mac/BSD platforms. Is this a special feature of the gcc c++ compiler? or is it standard C++? Where in the standard does it says so?
Unary operator ( * ) is used to declare a variable and it returns the address of the allocated memory. Pointers to an array points the address of memory block of an array variable. The following is the syntax of array pointers. datatype *variable_name[size];
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
int (*ptr)[10]; Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is 'pointer to an array of 10 integers'.
This value-initialization is standard C++.
The relevant standardeese is in C++98 and C++03 §5.3.4/15. In C++98 it was default-initialization, in C++03 and later it's value initialization. For your pointers they both reduce to zero-initialization.
C++03 §5.3.4/15:
– If the new-initializer is of the form
()
, the item is value-initialized (8.5);
In C++0x that paragraph instead refers to “the initialization rules of 8.5 for direct-initialization”, where in N3290 (the FDIS) you find about the same wording in §8.5/16.
Cheers & hth.,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With