简体   繁体   中英

How many bytes does a #define string (string literal) take?

#define STR "test1"

Why does this take 6 bytes?

sizeof(STR) = 6

最后有一个尾随'\\0'

It has nothing to do with #define . A character array would be the same size:

const char str[] = { "test1" };
sizeof (str) == 6

The reason this string is 6 bytes long is that strings in C have a terminating NUL character to mark the end.

a #define just does a text replacement before compiling.

#define STR "test1"
sizeof(STR);

is actually seen by the compiler as

sizeof("test1");

now why is that 6 and not 5? because there's a null terminator at the end of the string.

Strings in C are arrays of char s, with a null terminator ie they end with the \\0 . The common alternative is Pascal-style strings, where the string stores the array of char s without the null terminator, and stores the length of the string somewhere instead.

What the others said ... BUT

In C , preprocessing tokens take no space. It depends on how you use them

#define STR "test1"

char x[] = STR;         /* 6 bytes */
char *y = STR;          /* sizeof (char*) bytes (plus possibly 6 bytes) */
int ch = STR[3];        /* 1 byte (or sizeof (int), depending on how you look at it) */
if (ch == STR[1])       /* 1 byte (or sizeof (int) or no bytes or ...) */

printf("==>" STR "<==") /* 5 bytes ??? */

Why does this take 6 bytes?

Actually, it will take (6 bytes × the number of times you use it), because it's a preprocessor macro.

Try const char *STR = "test1" instead.

The latest C compiler has a feature to guess if the person writing the program is in a learning phase and give answers which make them search wider and deeper, and thus enrich their knowledge.

After programming for some time, depending of your learning, you might see the value go down to 5. ;-)

JK.. as someone else said, it symbolically nothing at the end which ironically takes a byte.

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