我对sizeof运营商有疑问
代码1:
int main()
{
int p[10];
printf("%d",sizeof(p)); //output -- 40
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码2:
int main()
{
int *p[10];
printf("%d",sizeof(*p)); //output -- 4
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在第一个代码中,p指向一个int数组.在第二个代码中,p指向一个指针数组.我无法理解为什么第一个代码o/p是40但第二个代码o/p是4认为两者都指向相同大小的数组?
以下程序的输出将为您提供有关类型大小和类型指针的一些提示和理解.
#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)
Run Code Online (Sandbox Code Playgroud)
现在回答你的问题:
>> in the first code p points to an array of ints.
>> in the second code p points to an array of pointers.
Run Code Online (Sandbox Code Playgroud)
你是对的.在代码中:2,要获取p指向的数组的大小,需要传递基址
printf("%d", (int)sizeof(p));
Run Code Online (Sandbox Code Playgroud)
而不是以下
printf("%d", (int)sizeof(*p)); //output -- 4
Run Code Online (Sandbox Code Playgroud)
以下是等效的:
*p, *(p+0), *(0+p), p[0]
Run Code Online (Sandbox Code Playgroud)
>> what's the difference between p[10] and
>> (*p)[10]...they appear same to me...plz explain
Run Code Online (Sandbox Code Playgroud)
以下是您的其他问题的答案:
int p[10];
_________________________________________
| 0 | 1 | 2 | | 9 |
| (int) | (int) | (int) | ... | (int) |
|_______|_______|_______|_________|_______|
int (*p)[10]
_____________________
| |
| pointer to array of |
| 10 integers |
|_____________________|
Run Code Online (Sandbox Code Playgroud)
基本上,你有一个指针数组.当你这样做时*p,你取消引用指向数组的第一个元素的指针.因此,类型将是int.sizeof(int*)恰好是你机器上的4.
编辑(澄清):
代码片段1,你正在抓住数组的大小.
代码片段2,您正在抓取指针数组的第一个元素指向的类型的大小.