Malachi
Malachi

Reputation: 2453

syntax for array of pointers in C++

So, I see that the practice for dynamic allocating of an array of pointers looks like this:

int **array = new int *[10];

And indeed, using syntax:

int *array[] = new int *[10];

results in error:

/Users/Malachi/Projects/playground/playground.gcc/src/pgccc-5/main.cpp:8: error: definition of variable with array type needs an explicit size or an initializer
    const char* test_array[];
                ^

I'm always more comfortable using pure pointer syntax anyway. However, what bothers me is lines like this:

int main(int argc, char *argv[])

are valid. I'm accustom to empty array brackets [] more or less aliasing out to a pointer type. It seems to me char *argv[] is subject to almost exactly the same constraints as my int *array[], so why is the syntax permitted in one scenario but not the other?

EDIT: It appears the simpler case of int array[] = new int[10] exhibits the same behavior

Upvotes: 0

Views: 111

Answers (3)

R Sahu
R Sahu

Reputation: 206577

I'm accustom to empty array brackets [] more or less aliasing out to a pointer type.

That's valid only in the declaration of a function argument.

void foo(int a[]);

is the same as:

void foo(int* a);

However, when declaring or defining variables, they are not the same.

int a[] = {1, 2, 3}; // Valid. Array of 3 ints

is not the same as

int* a = {1, 2, 3}; // Invalid syntax.

Exception

You can use a string literal to intialize a char array or char const*.

char s1[] = "string 1";
char const* s2 = "string 2";

However, you can't use (not in C++ anyway):

char* s2 = "string 2";

Upvotes: 0

luk32
luk32

Reputation: 16070

It's because function parameter declaration is something different than variable declaration.

An array can decay into a pointer for the first dimension.

You can explicitly express that function expects an array rather than a pointer through the declaration using [] notation in e.g int main(int argc, char *argv[]). They type doesn't matter:

void f(int* i[]) {}

is legal as well. This says "I want an array of pointers to ints". This is more expressive than:

void f(int** i) {}

Upvotes: 0

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

This one:

int *array[] = new int *[10];

is not a valid syntax. The reason the left side has a type of an array of pointers to int, and the right side has a type of a pointer to a pointer to int. So the assignment is not legal due to the different types of left and right sides.

On the other hand, arrays decay into pointers. It means, that when you declare a function in the form of:

void foo(int* arr[])

the compiler sees it as:

void foo(int** arr)

The rule above applies only for functions, but not for assignments like in the first example.

Upvotes: 1

Related Questions