2016-07-20 39 views
1
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字符需要1個字節」

」 ...地址:00F3F718"

「...地址:00F3F70C」,

我想地址之間的差異應該是1個字節,因爲這將是分離它們的數據的大小。爲什麼不是這樣?

+7

你把指針的地址。 – user2357112

回答

5

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

+1

@downvoter:請告訴我我錯在哪裏,以便改善它。 – songyuanyao

+1

我覺得這很清楚,謝謝! – Jeppe

0

您正在查看指針的地址pointerToFirstCharpointerToSecondChar。它們是指向char的指針;比較它們的的值,那些值將會相差1.您似乎已經在文本中編輯了這些值。

0

您正在打印指針變量的地址,而不是當前指針所持有的地址。

例如:pointerToFirstChar = 0xF8C2的

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

地址和它保持地址& myCharString [0] = 0xFE20

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

將您的代碼更新爲f ollows得到正確的結果。

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

相關問題