3

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]);

?

alk
  • 69,737
  • 10
  • 105
  • 255
PowerPack1
  • 67
  • 4
  • 4
    Try `sizeof(array)` versus `sizeof(&array[0])`. – EOF Dec 26 '16 at 09:45
  • 1
    @EOF and, ironically, that is exactly the difference. this is not the same case, however. – Sourav Ghosh Dec 26 '16 at 09:45
  • 1
    @SouravGhosh: No. *Exactly* the difference would be: `sizeof` *and* `_Alignof` *and* `&`. – EOF Dec 26 '16 at 09:47
  • @EOF I think slight misunderstanding, we're both on the same page, you're answering the title, while i was referring to the exact case in the question body. :) – Sourav Ghosh Dec 26 '16 at 09:50
  • "*problematic*" in which sense? – alk Dec 26 '16 at 10:37
  • Your two cases are semantically equal. The difference is in the impression it gives to the reader. The first case gives impression that the function expects an array, i.e. it will use indexation on it. The second case suggests that you are passing a pointer to a single element. – Marian Dec 26 '16 at 10:42

1 Answers1

8

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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261