为什么 char 似乎在数组中占用的 space 比其本身多

Why does a char seem to take more space in an array than by itself

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* 以打印出地址而不是字符串。

您正在查看 指针 pointerToFirstCharpointerToSecondChar 的地址。它们是指向 char 的指针;比较它们的 ,它们相差 1。您似乎已经在文本中编辑了它。

您正在打印指针变量的地址,而不是当前指针所在的地址。

例如:

&myCharString[0] = 0xFE20  
&myCharString[1] = 0xFE21  
&myCharString[2] = 0xFE23  
char *pointerToFirstChar = &(myCharString[0]);

pointerToFirstChar 的地址 = 0xF8C2 并且它保存地址 &myCharString[0] = 0xFE20

所以你打印的是 0xF8C2 而不是 0xFE20

按如下方式更新您的代码以获得正确的结果。

cout << "Value was " << pointerToFirstChar << ", address: " << (void *)&pointerToFirstChar[0] << endl; cout << "Value 2 was " << pointerToSecondChar << ", address:" << (void *)&pointerToSecondChar[0] << endl;

更多信息请关注下方link print address of array of char