为什么char似乎在数组中占用的空间多于自身

时间:2016-07-20 06:08:31

标签: c++ pointers char memory-address

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;

此输出:

  

&#34; char占用1个字节&#34;

     

&#34; ...地址:00F3F718&#34;

     

&#34; ...地址:00F3F70C&#34;,

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

3 个答案:

答案 0 :(得分:5)

PC = PC + 8&pointerToFirstChar,您没有获取&pointerToSecondChar数组元素的地址,而是获取局部变量char和{的地址{1}}。请注意,他们自己就是指针。

你可能想要:

pointerToFirstChar

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

答案 1 :(得分:0)

您正在查看指针 pointerToFirstCharpointerToSecondChar的地址。它们是char的指针;比较他们的,那些差异为1.您似乎已经在文本中对其进行了编辑。

答案 2 :(得分:0)

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

例如:

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

pointerToFirstChar = 0xF8C2的地址,它保存地址&amp; myCharString [0] = 0xFE20

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

按如下所示更新您的代码,以获得正确的结果。

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

有关详情,请点击以下链接 print address of array of char