string a= "Stack Overflow";
char b[]= "Stack Overflow";
cout<<sizeof(a)<<","<<sizeof(b)<<endl;
以上代码的输出是 4,15
因为“a”指向字符串,所以它的大小是我机器上字符串的 4。
'b' 也是指向字符串的指针,但为什么它的大小为 15(即 sizeof("Stack Overflow"))?
最佳答案
Since 'a' points to the string, it has size 4 that of a string on my machine.
不完全是。
a
是一个 字符串。它不是指针,因此不指向字符串。 string
在您的设置中的实现使得 sizeof(string)
为 4。
'b' is also pointer to string, but why it has size of 15 (i.e. of sizeof("Stack Overflow")) ?
不正确。
b
不是指向字符串的指针。它是一个 char
数组。线路
char b[]= "Stack Overflow";
相当于:
char b[15]= "Stack Overflow";
编译器推导出数组的大小并创建一个正确大小的数组。
关于c++ - C++中指向数组与字符串的指针的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47819708/