RadicalOne
RadicalOne

Reputation: 67

C - SizeOf Pointers

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

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?

Upvotes: 0

Views: 4333

Answers (4)

JackCColeman
JackCColeman

Reputation: 3807

In C (not C99) the sizeof operator is strictly a compile time calculation. so when sizeof (*p) [a dereferenced ptr to an integer] is evaluated then the size of int is four.

Note. the (*p) portion of that statement is a "cast" operator. So, sizeof is NOT a function call as in sizeof(xyz), rather it is like sizeof var_name or sizeof (int *).

When your program runs it changes the object pointed to by p, but the value of sizeof (*p) was already computed and hard-coded into your executable load module.

I think your confusion is that you were thinking that C would figure out what data type p was pointing to when your program runs.

Upvotes: 0

viki
viki

Reputation: 203

sizeof(*p) will print size of p which is 4 because of int but c is of char that's why it is 1

Upvotes: 0

user529758
user529758

Reputation:

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.

Upvotes: 6

Keith Thompson
Keith Thompson

Reputation: 263267

sizeof(*p) is the size of the int object to which p points.

Upvotes: 4

Related Questions