Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointer array initialization help

Tags:

c++

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?

like image 330
Roderick Taylor Avatar asked Aug 25 '11 07:08

Roderick Taylor


People also ask

How do I declare a pointer to an array in C?

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];

What is the correct way of initializing an array in C?

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.

How do you declare an array of 10 pointers pointing to integers?

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'.


1 Answers

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.,

like image 196
Cheers and hth. - Alf Avatar answered Oct 05 '22 11:10

Cheers and hth. - Alf