2011-11-25 93 views
2
int a[5]; 

cout << &a[1] << " " << &a[0] << endl; 
cout << (&a[1] - &a[0]); 

在上面的代碼,這是爲什麼&一[1] - &一個[0]等於1,而不是4?這些地址之間不應該有4個字節,因爲我們有一個int數組?C++指針運算

回答

8

不,指針差異在元素中,而不是在字節中。

+1

那麼簡單。 @ user974967:從長遠看書會便宜 – sehe

1

爲了得到它以字節爲單位(現場觀看https://ideone.com/CrL4z

int a[5]; 

cout << (a+1) << " " << (a+0) << endl; 
cout << (reinterpret_cast<char*>(a+1) - reinterpret_cast<char*>(a+0)); 
+0

哎呀,沒人看到那個忍者編輯我希望? – sehe

2

指針由有型的規模遞增。原因是因爲你想指向下一個項目。所以讓你更進一步。

int a[5]; 
int *ptr=&a[0]; 

// ptr is now pointing at first element. 

ptr+3; // now its pointing at 3rd element.