0

When we need to assign an array to pointer, we doing something like that.

int numbers[] = {7,5,9,3};
int *ptr = NULL;
ptr = &numbers[0];  // <<

Also we can do same thing by doing this.

int numbers[] = {7,5,9,3};
int *ptr = NULL;
ptr = numbers;  // <<

What is the difference between two ways ?
And which one is the Recommended ?

Lion King
  • 32,851
  • 25
  • 81
  • 143
  • IIRC, the term is "array [pointer] decay" - see http://stackoverflow.com/questions/1461432/what-is-array-decaying, perhaps – user2864740 Dec 06 '13 at 23:35
  • 1
    There's no difference. Pick whichever has your fancy. The former is explicit, the latter is short. – Fred Foo Dec 06 '13 at 23:35

3 Answers3

3

It's the same thing. The expression a[i] is the same as *(a + i), so &a[i] is the same as &*(a + i), which is defined to be identical to a + i (without even evaluating the dereference). For i = 0 this means that a is the same as &a[0]. The name of the array decays to a pointer to the first element of the array.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Thanks, but can you please Clarify this part `The name of the array decays to a pointer` – Lion King Dec 06 '13 at 23:49
  • @LionKing: When you use `numbers` as an expression (a so-called *id-expression*), then in most cases it's value is an `int` pointer which points to the first element of the array; it's value does *not* have array type. This is called "decay". There are no "array values" in C. – Kerrek SB Dec 06 '13 at 23:51
1

No difference (except when they are the oprand of sizeof operator). In both case you are assigning address of the first element of array. &numbers[0] assign the address of the first element of the array while numbers will decay to pointer to the first element of the array.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • 2
    It should be worth noting that although there is no difference in this case, there are times when `array` and `&array[0]` are not the same (e.g. when it is used as an operand to `sizeof`). – dreamlax Dec 06 '13 at 23:37
-3

They will both give you the same value, however there is slightly a difference. When you do

ptr = &numbers[0];

you are adding two unnecessary steps, a dereference and a "address of" operation, so using

ptr = numbers;

would be more performant, unless the compiler optimizes it away. It may be useful to think of int numbers[] = ...; as int *numbers = ...

clcto
  • 9,530
  • 20
  • 42
  • 1
    If a compiler doesn't produce the same output for both situations it might be time to find a new compiler. – dreamlax Dec 06 '13 at 23:42
  • "tr = numbers; would be more performant" - uggh... let us try wake up and live in the 21th century... –  Dec 06 '13 at 23:43