我的问题是,当我直接引用一个数组的索引时,我得到一个地址,但是当我通过 for 循环引用它时得到一个不同的地址。零索引的地址相同,但之后有所不同。我在使用 Nano 的 Arduino IDE 中。
代码:
void setup() {
Serial.begin(9600);
Serial.println("\nSerial connected.");
int luckyNumbers[5] = {2, 5, 9, 7, 3};
Serial.println("\nint luckyNumbers[5] = {2, 5, 9, 7, 3}\n");
Serial.println("Direct reference...");
Serial.print("luckyNumbers[0] = ");
Serial.println(long(&luckyNumbers[0]));
Serial.print("luckyNumbers[1] = ");
Serial.println(long(&luckyNumbers[1]));
Serial.print("luckyNumbers[2] = ");
Serial.println(long(&luckyNumbers[2]));
Serial.print("luckyNumbers[3] = ");
Serial.println(long(&luckyNumbers[3]));
Serial.print("luckyNumbers[4] = ");
Serial.println(long(&luckyNumbers[4]));
Serial.println("\n Now the for loop...");
for( int i = 0; i < 5; i++) {
Serial.print(" i = ");
Serial.print(i);
Serial.print(" @ memory address ");
Serial.println(long(&luckyNumbers + i));
}
}
void loop() {
//Do nothing. Just.... don't.
}
串行控制台读取:
Serial connected.
int luckyNumbers[5] = {2, 5, 9, 7, 3}
Direct reference...
luckyNumbers[0] = 2290
luckyNumbers[1] = 2292
luckyNumbers[2] = 2294
luckyNumbers[3] = 2296
luckyNumbers[4] = 2298
Now the for loop...
i = 0 @ memory address 2290
i = 1 @ memory address 2300
i = 2 @ memory address 2310
i = 3 @ memory address 2320
i = 4 @ memory address 2330
我一直在关注 CodeBeauty 的指针课程。这非常棒而且切中要害。当然,她用的是c++,我用的是wrapped c++。虽然我预计代码会因此而有所不同,其中一些你可以在我如何转换地址数据类型以打印到串行监视器中看到,但我想知道这些差异是否扩展到我如何使用 for 循环来收集地址。This 是我从中建模我的代码的视频。
我希望看到直接引用和增量引用的内存地址彼此相等。
提前感谢您抽出时间回答我的问题。