Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

arrays - C - SizeOf Pointers

char c[] = {'a','b','c'};
int* p = &c[0];
printf("%i
", sizeof(*p)); //Prints out 4
printf("%i
", sizeof(*c)); //Prints out 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because p is of type int *, so *p is of type int, which is apparently 4 bytes wide on your implementation.


And use %zu for printing size_t (what sizeof yields) if you don't want your program to invoke undefined behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...