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

我与影子孤独终老i 提交于 2019-11-29 17:39:48

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.

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.

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.

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