I know that in C++, the name of an array is just the pointer to the first element of the array. For example:
int foo[5];
=> foo is a pointer of type int, and it points to the first element in the array, which is a[0]
But then, we have this:
int (*foo)[5]
Here, foo is a pointer to an array of type. So is foo a pointer to a pointer (of type int)?
-
2No, it's a pointer to an array. Arrays are not pointers.Qaz– Qaz2012年10月17日 03:35:49 +00:00Commented Oct 17, 2012 at 3:35
-
This has to be a dupe, right?Carl Norum– Carl Norum2012年10月17日 03:37:33 +00:00Commented Oct 17, 2012 at 3:37
-
@CarlNorum, Oh, let me count the ways.Qaz– Qaz2012年10月17日 03:39:40 +00:00Commented Oct 17, 2012 at 3:39
-
Arrays are pointers with a bit more overhead like array size and padding.SwiftMango– SwiftMango2012年10月17日 04:39:26 +00:00Commented Oct 17, 2012 at 4:39
2 Answers 2
This is an array of five ints:
int a[5];
This is a pointer to an array of five ints:
int (*p)[5] = &a;
This is a pointer to an int:
int * q = a; // same as &a[0]
Comments
in C++, the name of an array is just the pointer to the first element of the array
That's not correct: a name of an array can be converted to a corresponding pointer type "for free", but it is definitely not a pointer. The easiest way you can tell is by comparing sizes of a pointer and of an array:
int foo[5];
int *ptr;
cout << sizeof(foo) << endl;
cout << sizeof(ptr) << endl;
Your second example is a pointer to an array of ints of size 5.
cout << sizeof(foo) << endl;
cout << sizeof(*foo) << endl;
In a 32-bit environment this prints 4 and 20, as expected.