I am preparing some presentation and I am curious if there is any other context (except of sizeof) where a variable of array type gives different behavior than a pointer to the first element of the array. I mean:
int a[5];
int *p = a;
printf("%d %d\n", sizeof(a), sizeof(p));
prints two different numbers. Is there any other similar situation where it matters whether I use an array or a pointer?
Is there a situation when an array is not converted to pointer except of sizeof?
From C99/C11, section 6.3.2.1:
Except when it is the operand of the
sizeof
operator, [the_Alignof
operator,] or the unary&
operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type"...
Note that _Alignof
is only in C11.
Is there any other similar situation where it matters whether I use an array or a pointer?
The above rule explains everything about the behaviour of arrays vs. pointers. However, there are several less-than-obvious implications of the conversion it describes.
For example, this doesn't compile:
void foo(int **a) { }
int b[5][10];
foo(b); // Compilation error; b becomes &b[0], which is pointer type,
// and thus doesn't then become &&b[0][0]
And neither does this:
int a[5];
int b[5];
a = b; // Compilation error; a becomes &a[0], which isn't an lvalue
One more thing.
int a[10];
int *pa;
There is one difference between an array name and a pointer that must be kept in mind. A pointer is a variable, so pa=a and pa++ are legal. But an array name is not a variable; constructions like a=pa and a++ are illegal.
The C programming language, Dennis M. Ritchie
There are a few other contexts where it is not converted such as unary &
, if we look at the draft C99 standard section 6.3.2.1
Lvalues, arrays, and function designators paragraph 3 it says:
Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With