Pointers - the difference between an array and a pointer

What is the difference between a , &a and the address of the first element a[0] ? Similarly, p is a pointer to an integer assigned with the address of the array. pointer[] will do pointer arithmetic and get the value according to the data type? Next, what value does * expect? Should it be a pointer?

 #include<stdio.h> int main() { int a[] = {5,6,7,8}; int *p = a; printf("\nThis is the address of a %u, value of &a %u, address of first element %u, value pointed by a %u", a, &a, &a[0], *a); printf("\nThis is the address at p %u, value at p %u and the value pointed by p %d", &p, p, *p); printf("\n"); } This is the address of a 3219815716, value of &a 3219815716, address of first element 3219815716, value pointed by a 5 This is the address at p 3219815712, value at p 3219815716 and the value pointed by p 5 
+3
source share
2 answers
 int a[]={5,6,7,8}; int *p= a; 

Note that in the case of arrays (in most cases), for example, the array a , ADDRESS_OF a matches ADDRESS_OF first element of the .ie array, ADDRESS_OF(a) matches ADDRESS_OF(a[0]) >. & is an ADDRESS_OF statement and, therefore, in the case of an array, a , &a and &a[0] are the same.

I have already emphasized that in most cases the name of the array translates to the address of its first element; one of the notable exceptions is that it is a sizeof operand, which is essential if malloc should work. Another case is that the array name is the operand of the operator and address. Here it is converted to the address of the entire array . Who cares? Even if you think that the addresses will be โ€œthe sameโ€ in some way, the critical difference is that they are of different types. For an array of n elements of type T, the address of the first element is of type 'pointer to T; the address of the entire array is of type 'pointer to an array of n elements of type T; clearly very different.

Here is an example:

 int ar[10]; int *ip; int (*ar10i)[10]; /* pointer to array of 10 ints */ ip = ar; /* address of first element */ ip = &ar[0]; /* address of first element */ ar10i = &ar; /* address of whole array */ 

For more information, you can refer to The C Book.

+3
source

In C, pointers and arrays are very similar. In your example, the difference between a and p is that sizeof a is 4 * (sizeof int) , and sizeof p is the size of the pointer, maybe 4 or 8 depending on your platform. In addition, C makes no distinction between pointers and arrays. Therefore, a [0], * a, p [0] and * p are all the same. In some cases, even 0 [p] is acceptable. It just creates pointer arithmetic.

+2
source

All Articles