jack
jack

Reputation: 145

sizeof operator in c

I have a question regarding this code:

int main()
{
    printf("%d",sizeof(""));
}

It prints 1, why?

Upvotes: 2

Views: 338

Answers (7)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215607

Your program actually has undefined behavior because %d is not a valid format specifier for size_t expressions. You should use %zu or else cast the result of sizeof down to int. Otherwise the existing answers are okay.

Upvotes: 0

jamesdlin
jamesdlin

Reputation: 90174

The string literal "" is of type char[1] (a char array of one element, the NUL byte), not as char*/const char*. Therefore sizeof yields the size of the array, which is 1 byte.

Upvotes: 2

Benny Tjia
Benny Tjia

Reputation: 4883

In C, sizeof operator returns the size of a datatype in a number of bytes. In your case, an empty "" costs you 1 byte, and therefore it returns value 1.

Upvotes: 0

Coleman S
Coleman S

Reputation: 498

I interpreted the author's question to mean why 1 is printed instead of 4 or 8 (pointer size), not why is the size of a string == number consecutive non-zero bytes plus 1.

main(){printf("%d", sizeof((const char *)""));}

The output of the above program is 8 (pointer size on my machine). In this case, the compiler treats "" as it would be treated in a case like this: { const char *pointer = ""; }, not like this { char c[] = ""; }. (If you're familiar with x86 asm, its essentially lea vs. mov) The latter reserves 1 byte for a "buffer" on the stack, initialized to '\0'.

Upvotes: 4

Dair
Dair

Reputation: 16250

"" = \0 (Null character). Which is 1 byte. Therefore the size of it is 1.

Upvotes: 4

hookenz
hookenz

Reputation: 38987

"" == empty string or null terminated pointer to character.

It prints 1 because of the null terminator.

i.e.

"" really equals '\0'

Upvotes: 0

N.R.S.Sowrabh
N.R.S.Sowrabh

Reputation: 725

Its the string containing the \0 (Null) character, which has 1 Byte size.

Upvotes: 7

Related Questions