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

こ雲淡風輕ζ 提交于 2019-11-28 11:41:28

问题


char * test = "test";
cout << sizeof(test);


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

Running this on visual studio 2010, why is the output 45?
Shouldn't test be a string literal and the sizeof a string literal be the number of character elements in the string literal including the terminating null character?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/16567650/c-simple-sizeof-difference-between-char-array-and-char-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!