tags:

views:

207

answers:

7
#define STR "test1"

Why does this take 6 bytes?

sizeof(STR) = 6

+17  A: 

There is a trailing '\0' at the end.

DigitalRoss
@DigitalRoss: that is what I was thinking....thanks.
Tommy
+5  A: 

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.

Ben Voigt
That's not an array, it's a pointer to a string literal, and `sizeof(str)` will return the size of the pointer type for your machine.
Carl Norum
What this meant to say is that `const char str[] = "test1";` is the same as `const char str[] = {'t','e','s','t','1','\0'};`
aschepler
Umm, yeah. I feel really horrible, especially since I thought about the difference between sizeof array and sizeof pointer before typing the answer, and then my fingers hit the wrong keys anyways.
Ben Voigt
+2  A: 

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.

Michael Williamson
Speaking of Pascal strings in the context of C and C++ and string literals, is terribly misleading.
Mark Ransom
+5  A: 

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.

miked
+1  A: 

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 ??? */
pmg
A: 

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.

Rajan
+1  A: 
Seth
It's unspecified whether identical string literals are distinct objects. I.e. the value of the expression `"test1" == "test1"` could be true or false. This can even depend on compiler settings.
MSalters