Lucky
Lucky

Reputation: 575

What is the difference between p = *a[0] and p=&a[0]

#define N 20
int a[2N], i, *p, sum;

p = a;


/* p=a is equivalent to p = *a[0];
• p is assigned 300.
• Pointer arithmetic provides an alternative to array indexing.
• p=a; is equivalent to p=&a[=]; (p is assigned 300)

Here I am not getting how p=*a[0] and p=&a[0] are same? *a[0] references the element at the memory address.

Upvotes: 2

Views: 1655

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

The meaning of p = &a[0] is as follows

For example :

 int a[4];
                        a[0]  a[1]  a[2]  a[3]
            a --------> [   ][    ][    ][    ]

Equivalents

 // Reference
 &a[0] = a;
 &a[1] = a+1; 
 ...
 &a[3] = a+3;

 // Value
 a[0]  = *a
 a[1]  = *(a+1)
 ..
 a[3]  = *(a+3)

In arrays of C programming, name of the array always points to the first element of an array. Here, address of first element of an array is &a[0]. Also, a represents the address of the pointer where it is pointing i.e., base address . Hence, &a[0] is equivalent to a, so p = a or p = &a[0] both are same.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

Point 1

Do your understand, here int a[2N] is invalid code?

This 2N does not mean 2*N, rather this N is considered as a suffix (to integer literal 2) which is invalid.

Thanks to Mr @ Lưu Vĩnh Phúc for the comment below.

If you wanted something like int a[40], write int a [2*N]

Point 2

p=*a[0] and p=&a[0] are same

No, they're not same. Actually, with the current code snippet, *a[0] is invalid.

FWIW, p = a; and p = &a[0]; are same, because the array name represents the base address, i.e., the address of the first element in the array.

Upvotes: 5

user4520
user4520

Reputation: 3457

p = a and p = &a[0] are indeed equivalent. In this case, you assign the address of the first element in the array to p (because the name of the array = pointer to its first element). p=*a[0] and p=&a[0] are not the same; *a[0] requires that a be an array of pointers, and dereferences its first member.

Upvotes: 1

Related Questions