C++ simple sizeof difference between char array and char pointer

后端 未结 4 1203
难免孤独
难免孤独 2020-12-22 06:26
char * test = \"test\";
cout << sizeof(test);


char test2[] = \"test\";
cout << sizeof(test2);

Running this on visual studio 2010, why

相关标签:
4条回答
  • 2020-12-22 06:52

    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.

    0 讨论(0)
  • 2020-12-22 06:55

    test is a pointer to a string literal, not a string literal (a char[]):

    • the sizeof(char*) is 4, relating to test
    • the sizeof(char[5]) is 5, relating to test2[]

    hence 45 is the output.

    0 讨论(0)
  • 2020-12-22 06:55

    The first one displays the size of the pointer, not the array. In the second case, you are displaying the size of the array.

    0 讨论(0)
  • 2020-12-22 06:59

    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.

    0 讨论(0)
提交回复
热议问题