开发者

Pointers - Difference between Array and Pointer

What is the difference between a, &a and th开发者_Python百科e address of first element a[0]? Similarly p is a pointer to an integer assigned with array's address. Would pointer[] do the pointer arithmetic and fetch the value as per the datatype? Further 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


int a[]={5,6,7,8};
int *p= a;

Note that in case of arrays(In most cases), say array a, the ADDRESS_OF a is same as ADDRESS_OF first element of the array.ie, ADDRESS_OF(a) is same as ADDRESS_OF(a[0]). & is the ADDRESS_OF operator and hence in case of an array a, &a and &a[0] are all the same.

I have already emphasized that in most cases, the name of an array is converted into the address of its first element; one notable exception being when it is the operand of sizeof, which is essential if the stuff to do with malloc is to work. Another case is when an array name is the operand of the & address-of operator. Here, it is converted into the address of the whole array. What's the difference? Even if you think that addresses would be in some way ‘the same’, the critical difference is that they have different types. For an array of n elements of type T, then the address of the first element has type ‘pointer to T’; the address of the whole array has type ‘pointer to array of n elements of type T’; clearly very different.

Here's an example of it:

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 The C Book.


In C, pointers and arrays are very similar. In your example the only difference between a and p is that sizeof a is 4 * (sizeof int) and sizeof p is the size of a pointer, probably 4 or 8 depending on your platform. Other than that, C does not really differentiate between pointers and arrays. So a[0], *a, p[0] and *p are all the same. In some cases, even 0[p] is valid. It just makes pointer arithmetics.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜