int main() { int var = 20;//实际变量声明 int *ip;//指针变量声明 ip = &var;// 在指针变量中存储var的地址 cout << " Value of var variable:"; cout << var << endl; //输出在指针变量中存储的地址 cout << "Address stored in ip variable:"; cout << ip << endl; //访问指针中地址的值 cout << "Value of *ip variable:"; cout << *ip << endl; return 0; }
当上面的代码被编译和执行时,它会产生下列结果:
1 2 3
Value of var variable: 20 Address stored in ip variable: 0xbfc601ac Value of *ip variable: 20
int main() { int var[MAX] = {10, 100, 200}; int *ptr; //指针中的数组地址 ptr = var; for (int i = 0; i < MAx; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] ="; cout << *ptr <,endl; //移动到下一个位置 ptr++; } return 0; }
当上面的代码被编译和运行时,它会产生下列结果:
1 2 3 4 5 6
Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200
int main() { int var[MAX] = {10, 100, 200}; int *ptr; //指针中最后一个元素的地址 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; //移动到下一个位置 ptr--; } return 0; }
当上面的代码被编译和执行时,它会产生下列结果:
1 2 3 4 5 6
Address of var[3] = 0xbfdb70f8 Value of var[3] = 200 Address of var[2] = 0xbfdb70f4 Value of var[2] = 100 Address of var[1] = 0xbfdb70f0 Value of var[1] = 10
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // 指针中第一个元素的地址 ptr = var; int i = 0; while ( ptr <= &var[MAX - 1] ) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // 指向上一个位置 ptr++; i++; } return 0; }
当上面的代码被编译和执行时,它会产生下列结果:
1 2 3 4 5 6
Address of var[0] = 0xbfce42d0 Value of var[0] = 10 Address of var[1] = 0xbfce42d4 Value of var[1] = 100 Address of var[2] = 0xbfce42d8 Value of var[2] = 200