简体   繁体   中英

sizeof operator in c

I have a question regarding this code:

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

It prints 1 , why?

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

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

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'.

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.

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

It prints 1 because of the null terminator.

ie

"" really equals '\0'

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM