Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is p = array the same as p = &array[0]?

int numbers[20];
int * p;    

Are the two assignments below the same?

p = numbers;
p = &numbers[0];
like image 734
user784637 Avatar asked Oct 08 '11 17:10

user784637


People also ask

Can an array be a pointer?

An array is a pointer, and you can store that pointer into any pointer variable of the correct type. For example, int A[10]; int* p = A; p[0] = 0; makes variable p point to the first member of array A.

How to declare an array AS a pointer in C?

To declare an array in C, we use the syntax: dataType arrName[arrSize]; Here, the dataType refers to the type of array, which can be an integer, float, a character, or a pointer.

How is the 2nd element in an array accessed based on pointer notation*?

How is the 2nd element in an array accessed based on pointer notation? a[2] is equivalent to *(a + 2) in pointer notation.


2 Answers

Yes both are same.

In this case, Name of the array decays to a pointer to its first element.

Hence,

p = numbers;       //Name of the array

is same as:

p = &numbers[0];   //Address of the First Element of the Array
like image 175
Alok Save Avatar answered Oct 08 '22 02:10

Alok Save


Yes, they are the same. When an array's name is invoked in an rvalue context, it decays to a pointer to its first element.

like image 34
Puppy Avatar answered Oct 08 '22 04:10

Puppy