Jan 22, 2014

[C][C++] Pointer vs. Array

Pointer == Array ?? Not really



void bar(int arr[][3], int m, int n)
//same
void bar(int (*arr)[3], int m, int n)
//-------
// int arr[][3][4] => int (*arr)[3][4], et cetera. same
== quote from Keith Thompson ==
Arrays are not pointers, and pointers are not arrays.
Certain features of the language seem to conspire to make you think they’re equivalent. They are not.

An expression of array type, in most contexts, is implicitly converted to a pointer to the first element of the array object.

There are three cases where this conversion doesn’t occur:
1. When the array is the operand of a unary “&” operator
(so &arr yields the address of the array, not the address of its first element; same address, different type).
2. When the array is the operand of a unary “sizeof” operator (so sizeof arr yields the size of the array, not the size of a pointer).
3. When the array is a string literal in an initializer used to initialize an array object (so char arr[6] = “hello” works).

Another rule: When you declare a function parameter with array type, it’s really of pointer type.
void foo(int arr[]);
really means this:
void foo(int *arr);
This isn’t a conversion, it’s a compile-time translation.

Finally, the indexing operator [] doesn’t take an array operand.
It takes two operands, a pointer and an integer.
p[i] is, by definition, equivalent to *(p+i).
(And it’s commutative, so arr[42] is equivalent to 42[arr]. Now that you know that, please don’t use it.)

So when you write arr[i], where arr is declared as an array object, the indexing operator gets a pointer to the first element of arr.
And when you pass an array to a function:
int arr[10];
func(arr);
you’re really passing an int*, not an array.
This isn’t because it’s a function call, it’s because the expression is converted *before* the call.
The same conversion would happen in any context other than the three that I mentioned.

So when you say that “Arrays passed to functions are converted to pointers”,
that’s really just one case of a more general rule.

Reference:
Pointers to arrays in C
Row-major_order
making-sense-of-pointers
reading-c-type-declarations
non-constant-global-initialization-in-c-and-c

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.