开发者

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.

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).


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:

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

and one rather wonders why you didn't?


For the above question answer is 4.
Here you are type casting an integer pointer to a char pointer.
That means now the integer pointer is holding chars.
For the sizeof operator default argument is int.
When you are passing like sizeof((char *)(*p)) then it treats as sizeof('a'). This char a is promoted to an int. That's why you are getting 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). 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜