C - 指针大小 [英] C - SizeOf Pointers
本文介绍了C - 指针大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
char c[] = {'a','b','c'};
int* p = &c[0];
printf("%i\n", sizeof(*p)); //Prints out 4
printf("%i\n", sizeof(*c)); //Prints out 1
我对这部分代码感到非常困惑.p 和 c 都表示数组 c 在第 0 个索引处的地址.但是为什么 sizeof(*p) 会打印出 4?不应该是1吗?
I am extremely confused about this section of code. Both p and c represent the address of the array c at the 0th index. But why does sizeof(*p) print out 4? Shouldn't it be 1?
推荐答案
因为 p
是 int *
类型,所以 *p
是int
类型,在您的实现中显然是 4 个字节宽.
Because p
is of type int *
, so *p
is of type int
, which is apparently 4 bytes wide on your implementation.
如果您不希望程序调用未定义的行为,请使用 %zu
打印 size_t
(sizeof
产生的结果).
And use %zu
for printing size_t
(what sizeof
yields) if you don't want your program to invoke undefined behavior.
这篇关于C - 指针大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文