Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sizeof return different values for same string in C? [duplicate]

Possible Duplicate:
Sizeof doesn't return the true size of variable in C
C -> sizeof string is always 8

Sizeof prints out 6 for:

printf("%d\n", sizeof("abcde"));

But it prints out 4 for:

char* str = "abcde";
printf("%d\n", sizeof(str));

Can someone explain why?

like image 484
Kobi Avatar asked Mar 20 '26 20:03

Kobi


2 Answers

The string literal "abcde" is a character array. It is 6 bytes long, including the null terminator.

A variable of type char* is a pointer to a character. Its size is the size of a pointer, which on 32-bit systems is 4 bytes. sizeof is a compile time operation, so it only looks at the variable's static type, which in this case is char*. It has no idea what's being pointed to.

† Except in the case of variable-length arrays, a feature introduced in the C99 language standard

like image 156
Adam Rosenfield Avatar answered Mar 23 '26 16:03

Adam Rosenfield


First example, sizeof() return the length of the plain string.
Second example, sizeof() return the size of the pointer -> 32bits so 4 bytes.

like image 32
TridenT Avatar answered Mar 23 '26 14:03

TridenT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!