指针和数组在许多情况下是可互换的, 例如,指向数组开头的指针,可以使用指针算法或数组样式索引来访问该数组。
示例:
#include <iostream>
using namespace std;
const int MAX = 4;
int main () {
int var1[MAX] = {10, 100, 200,300};
int *ptr;
ptr = var;
for (int i = 0; i < MAX; i++) {
cout << "Address of var1[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var1[" << i << "] = ";
cout << *ptr << endl;
ptr++;
}
return 0;
}
输出结果:
Address of var1[0] = 0xbfa088b0
Value of var1[0] = 10
Address of var2[1] = 0xbfa088b4
Value of var1[1] = 100
Address of var1[2] = 0xbfa088b8
Value of var1[2] = 200
Address of var1[3] = 0xbfa088bc
Value of var1[3] = 300