如何sizeof操作符的工作在C [英] How sizeof operator works in c
问题描述
我想知道如何sizeof操作符在C.In工作belown $ C $词我期望得到输出1,但得到4自从p被指向第一的位置,并在第一的位置有性格和它的大小应该是
的main()
{所以char a [9] =阿密特;
为int * p =&放大器;一个;
的printf(%D的sizeof((字符*)(* P)));
}
没有,你问一个字符的指针的也就是4在你实现的规模。
这是因为你铸造间接引用 INT
指针 P
到字符
指针然后要求的的大小。
将它分解:
的sizeof((字符*)(* P))
| \\ __ /
| \\ _提领p来得到一个int。
\\ ___________ /
\\ _____将其转换成一个char *(大小= 4)。
如果你想治疗的第一个字符的 INT
(这是,毕竟,你反正已经投了字符数组),你应该使用:
的sizeof(*((字符*)(P)))
这是 INT
指针,转换回一个字符
指针和然后取消引用。
最新的是的下降:
的sizeof(*((字符*)(P)))
| \\ ________ /
| \\ _获得由对一个char *(一个int *)
\\ ___________ /
\\ _____提领,要得到一个char(大小= 1)。
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.
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.
That's because you're casting the dereferenced int
pointer p
to a char
pointer then asking for the size of that.
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:
sizeof(*((char*)(p)))
That is the int
pointer, cast back to a char
pointer, and then dereferenced.
Breaking that down:
sizeof(*((char *)(p)))
| \________/
| \_ Get a char * from p (an int *)
\___________/
\_____ Dereference that to get a char (size = 1).
这篇关于如何sizeof操作符的工作在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!