以下程序的输出将为您提供有关类型大小和类型指针的一些提示和理解。
#include <stdio.h>
int main(void)
{
int p1[10];
int *p2[10];
int (*p3)[10];
printf("sizeof(int) = %d\n", (int)sizeof(int));
printf("sizeof(int *) = %d\n", (int)sizeof(int *));
printf("sizeof(p1) = %d\n", (int)sizeof(p1));
printf("sizeof(p2) = %d\n", (int)sizeof(p2));
printf("sizeof(p3) = %d\n", (int)sizeof(p3));
return 0;
}
int p[10]; => 10 consecutive memory blocks (each can store data of type int) are allocated and named as p
int *p[10]; => 10 consecutive memory blocks (each can store data of type int *) are allocated and named as p
int (*p)[10]; => p is a pointer to an array of 10 consecutive memory blocks (each can store data of type int)
现在来回答您的问题:
>> in the first code p points to an array of ints.
>> in the second code p points to an array of pointers.
您说得很对。在代码2中,为了获取p指向的数组的大小,需要传递基地址。
printf("%d", (int)sizeof(p));
而不是以下内容
printf("%d", (int)sizeof(*p)); //output -- 4
以下表达式是等价的:
*p, *(p+0), *(0+p), p[0]
>> what's the difference between p[10] and
>> (*p)[10]...they appear same to me...plz explain
以下是对您其他问题的回答:
int p[10];
_________________________________________
| 0 | 1 | 2 | | 9 |
| (int) | (int) | (int) | ... | (int) |
|_______|_______|_______|_________|_______|
int (*p)[10]
_____________________
| |
| pointer to array of |
| 10 integers |
|_____________________|
*p
与p[0]
相同。因此,sizeof(*p)
与sizeof(p[0])
相同,都是指针的大小。 - pmg