int main() {
string bucky[2];
bucky[0] = "hello";
bucky[1] = "world";
string *bp0 = &bucky[0];
string *bp1 = &bucky[1];
cout << "bp0 is at " << bp0 << " element is " << *bp0 << endl;
cout << "bp1 is at " << bp1 << " element is " << *bp1 << endl;
bp0++;
cout << "bp0 is now at " << bp0 << " element is " << *bp0 << endl;
cout << "bp1 is now at " << bp1 << " element is " << *bp1 << endl;
}
最后两行显示元素 1 和元素 2 现在共享相同的值和相同的地址?我理解正确吗?另外,第一个元素的地址在我将其递增 1 后会发生什么变化?
最佳答案
The last two lines shows that element 1 and element 2 now shares the same value, and the same address?
bp0
和 bp1
指向内存中的同一位置,因此指针具有相同的值。显然,它们指向的东西也必须相同,因为给定地址在内存中只有一个地方。
what happens to the address of the first element after I incremented it by one?
您正在将指向第一个元素的指针递增一个。当你这样做时,你会得到第二个元素的地址。指针算法是这样设置的:当您将索引 x
指向一个数组并向指针添加一个整数 y
时,您最终得到一个指向元素 x+y
.
只要 x+y
是非负的,并且低于数组元素的数量,这对正负 y
都有效。
关于c++ - 地址加1后第二个元素的值和第一个元素的值一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37362790/