How does sizeof() work for char* (Pointer variables)?
Solution 1
sizeof(s1)
is the size of the array in memory, in your case 20 chars each being 1 byte equals 20.
sizeof(s)
is the size of the pointer. On different machines it can be a different size. On mine it's 4.
To test different type sizes on your machine you can just pass the type instead of a variable like so printf("%zu %zu\n", sizeof(char*), sizeof(char[20]));
.
It will print 4
and 20
respectively on a 32bit machine.
Solution 2
sizeof(char *)
is the size of the pointer, so normally 4 for 32-bit machine, and 8 for 64-bit machine.
sizeof
an array, on the other hand, outputs the size of the array, in this case, 20*sizeof(char) = 20
One more thing, you should use %zu
for size_t
type in printf
format.
printf("%zu %zu\n", sizeof(s1), sizeof(s));
Solution 3
The sizeof
operator returns the size of a type. The operand of sizeof
can either be the parenthesized name of a type or an expression but in any case, the size is determined from the type of the operand only.
sizeof s1
is thus stricly equivalent to sizeof (char[20])
and returns 20.
sizeof s
is stricly equivalent to sizeof (char*)
and returns the size of a pointer to char
(64 bits in your case).
If you want the length of the C-string pointed by s
, you could use strlen(s)
.
Solution 4
8 is the size of a pointer, an address. On 64 bit machine it has 8 bytes.
Solution 5
If you are on a 64 bit computer, the memory addresses are 64 bit, therefore a 64 bit (8 bytes x 8 bits per byte) numeric value must be used to represent the numeric pointer variable (char*).
In other words, sizeof() works the same way for pointers as for standard variables. You just need to take into account the target platform when using pointers.
Related videos on Youtube
cloudyFan
Updated on July 09, 2022Comments
-
cloudyFan 6 months
I have a C code:
char s1[20]; char *s = "fyc"; printf("%d %d\n", sizeof(s1), sizeof(s)); return 0;
It returns
20 8
I'm wondering how does the 8 come from, thanks!
-
Chandra Shekhar over 3 yearsJust had a doubt what if we are to find sizeof(*s) ? it is giving me 1 byte but it should have been 3 bytes for "fyc". Kindly clarify this doubt.
-
Suri almost 2 years@ChandraShekhar That's because
char* s
is pointing to the first character of "fyc". So if you printf*s
, you get the first character of "fyc" which is 'f'. Individual character weighs 1 byte. That's why you got 1 byte.