Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c - Pointers - Difference between Array and Pointer

What is the difference between a, &a and the 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("
This 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("
This is the address at p %u, value at p %u and the value pointed by p %d", &p, p, *p);
printf("
");
}

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...