简体   繁体   English

sizeof 运算符在 c 中的工作原理

[英]How sizeof operator works in c

I wanted to know how sizeof operator works in C.In belown code i am expecting to get output 1 but getting 4.Since p is pointing to first location and at first location there is character and its size should be one.我想知道 sizeof 运算符在 C 中是如何工作的。在下面的代码中,我期望得到 output 1 但得到 4。因为 p 指向第一个位置,并且在第一个位置有字符,它的大小应该是一个。

main()
{

char a[9]="amit";
int *p=&a;
 printf("%d",sizeof((char *)(*p)));
 }

No, you're asking for the size of a character pointer which is 4 in your implementation.不,您要求的字符指针的大小在您的实现中为 4。

That's because you're casting the dereferenced int pointer p to a char pointer then asking for the size of that.那是因为您将取消引用的int指针p转换为char指针,然后询问它的大小。

Breaking it down:分解它:

sizeof((char *)(*p))
       |       \__/
       |         \_ Dereference p to get an int.
       \___________/
             \_____ Convert that to a char * (size = 4).

If you want to treat the first character of your int (which is, after all, a character array you've cast anyway), you should use:如果你想处理你的int的第一个字符(毕竟这是一个你已经投射的字符数组),你应该使用:

sizeof(*((char*)(p)))

That is the int pointer, cast back to a char pointer, and then dereferenced.那是int指针,转换回char指针,然后取消引用。

Breaking that down:打破

sizeof(*((char *)(p)))
       | \________/
       |         \_ Get a char * from p (an int *)
       \___________/
             \_____ Dereference that to get a char (size = 1).

You are getting the size of the result of the cast (char *) , which is a char * with size of 4. Of course you could just have said:您将获得强制转换结果的大小(char *) ,这是一个大小为 4 的 char *。当然您可以说:

 printf( "%d", sizeof(a[0]) );

and one rather wonders why you didn't?有人想知道你为什么不这样做?

For the above question answer is 4.对于上述问题,答案是 4。
Here you are type casting an integer pointer to a char pointer.在这里,您将 integer 指针类型转换为 char 指针。
That means now the integer pointer is holding chars.这意味着现在 integer 指针正在保存字符。
For the sizeof operator default argument is int.对于 sizeof 运算符,默认参数是 int。
When you are passing like sizeof((char *)(*p)) then it treats as sizeof('a') .当您像sizeof((char *)(*p))一样传递时,它会将其视为sizeof('a') This char a is promoted to an int.这个 char a 被提升为 int。 That's why you are getting 4.这就是你得到4的原因。

Yes, on a 32 bit system the piece of code should show the size of p to be 4.On a 16 bit it would show 2(not being highly used in application world these days, but can be a used in embedded world based on the requirement of a system).是的,在 32 位系统上,这段代码应该显示p 的大小为 4。在 16 位上,它会显示 2(这些天在应用程序世界中没有被高度使用,但可以在嵌入式世界中使用系统的要求)。 You have done a cast to a char , this will affect the data representation but not the memory occupied by the pointer pointing to your data.您已经对 char 进行了强制转换,这将影响数据表示,但不会影响指向数据的指针占用的 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM