char * test = \"test\";
cout << sizeof(test);
char test2[] = \"test\";
cout << sizeof(test2);
Running this on visual studio 2010, why
on a 32-bit system, the size of a pointer is 32 bits or 4 bytes and therefore, size of test is 4. On the other side, test2 is an array with a NUL terminating character and it's size is 5.
test
is a pointer to a string literal, not a string literal (a char[]
):
sizeof(char*)
is 4
, relating to test
sizeof(char[5])
is 5
, relating to test2[]
hence 45
is the output.
The first one displays the size of the pointer, not the array. In the second case, you are displaying the size of the array.
The first test
is a pointer to char. The size of a pointer depends on your architecture, but is usually 4 or 8 bytes. In your case it causes the "4". Note that assigning an string literal to a char*
is inherently unsafe and you should always assign it to char const*
instead.
The second test2
is actually an array of 5 characters. The size of an array is the number of its elements times their size. In your case it causes the "5".
Taken together you get an output of "45", since you never write anything else to the output stream (like a newline).
This makes sense, once you realize that by writing char test* = "test";
you ask the compiler to put a pointer to a string somewhere else on the stack. With char test2[] = "test";
you ask it to put a copy of the whole string on the stack - after all every character in your string has to be put in the array.
This is especially important if you wish to change your string: Changing the actual string literal if forbidden, because it may be reused (by yourself or the compiler) at some other point in your code, which is also the reason why you should always use char const*
when referring to a string literal. You will therefore have to create an array with its own copy of the string literal and change that.