简体   繁体   中英

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

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.

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

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 eg 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) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM