gpt4 book ai didi

c++ - 为什么 char 在数组中占用的空间似乎比它本身占用的空间更多

转载 作者:行者123 更新时间:2023-11-30 01:10:14 25 4
gpt4 key购买 nike

char testChar = 'a';
char myCharString[] = "asd";
char *pointerToFirstChar = &(myCharString[0]);
char *pointerToSecondChar = &(myCharString[1]);
cout << "A char takes " << sizeof(testChar) << " byte(s)";
cout << "Value was " << pointerToFirstChar << ", address: " << &pointerToFirstChar << endl;
cout << "Value 2 was " << pointerToSecondChar << ", address:" << &pointerToSecondChar << endl;

这个输出:

"A char takes 1 byte"

"... address: 00F3F718"

"... address: 00F3F70C",

我认为地址之间的差异应该是 1 个字节,因为那将是分隔它们的数据的大小。为什么不是这样?

最佳答案

&pointerToFirstChar&pointerToSecondChar,你获取的不是 char 数组元素的地址,而是局部变量的地址pointerToFirstCharpointerToSecondChar。请注意,它们本身就是指针。

你可能想要:

cout << "Value was " << pointerToFirstChar << ", address: " << static_cast<void*>(pointerToFirstChar) << endl;
cout << "Value 2 was " << pointerToSecondChar << ", address:" << static_cast<void*>(pointerToSecondChar) << endl;

请注意,您需要将它们转换为 void* 以打印出地址而不是字符串。

关于c++ - 为什么 char 在数组中占用的空间似乎比它本身占用的空间更多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38473494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com