0
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?

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Or convert to int and use "%d" or "%i" if your implementation (coughMicrosoftcough) doesn't support "%zu".
@KeithThompson Yup :) (MS would seriously need to start living in the XXIth century and support at least C99...)
Or, better, convert to unsigned long and use "%lu"
@KeithThompson why does int p pointer accept address of char .this code int* p = &c[0]. i though only void* pointers could take any type
@CholthiPaulTtiopic: It doesn't. Given char c[10], gcc warns initialization from incompatible pointer type
4

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

Comments

0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.