Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a situation when an array is not converted to pointer except of sizeof? [duplicate]

Tags:

c

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?

like image 371
Marian Avatar asked Feb 23 '14 16:02

Marian


3 Answers

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
like image 160
Oliver Charlesworth Avatar answered Oct 20 '22 22:10

Oliver Charlesworth


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

like image 4
sergej shafarenka Avatar answered Oct 20 '22 21:10

sergej shafarenka


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.

like image 3
Shafik Yaghmour Avatar answered Oct 20 '22 22:10

Shafik Yaghmour