Are "array" and "&array[0]" completely interchangeable?

354 views Asked by At

Yes, it has been asked before, many times, but I wanna know which one is more advisable?

typedef struct {
    int a;
    int addr[8];
} usr_command;

usr_command* p_usr_command;

int foo(int* parameter)
{}

So which one is less prone to be problematic?

foo(p_usr_command->addr);

or

foo(&p_usr_command->addr[0]);

?

1

There are 1 answers

0
Sourav Ghosh On

In this case ( passing an array name vs. passing the address of the first object in the array as function argument), both the snippets are equivalent.

Quoting C11, chapter §6.3.2.1, Lvalues, arrays, and function designators (emphasis mine)

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’’ that points to the initial element of the array object and is not an lvalue. [....]

However, in general, they are not the same.

  • array is an array of type int [8]
  • &(array[0]) is a pointer, type int *

As already suggested by EOF in his comment, try passing both variants to the sizeof operator and check the result to get the hands-on output.