开发者

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

#define STR "test1"

Why does this tak开发者_如何学Ce 6 bytes?

sizeof(STR) = 6


There is a trailing '\0' at 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.


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.


Strings in C are arrays of chars, with a null terminator i.e. they end with the \0. The common alternative is Pascal-style strings, where the string stores the array of chars 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜