[英]Pointer to an array,why is this the address of the last element?
我正在使用教程point.com示例。
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the last element in pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the previous location
ptr--;
}
return 0;
那么,為什么&var[MAX - 1]
而不為什么&var[MAX]
? 如果我們不使用參考,是否有可能以其他方式解決此問題?
因為C ++中的數組是從零開始的,即從0
開始到n-1
結束。 var[MAX]
是超出數組末尾的元素,因此越界也是無法定義的行為。
var { 10, 100, 200 }
index ^0 ^1^ ^2^ ^3?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.