Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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 = ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top