之前我们理解指针数组概念,让我们考虑下面的例子,这使得使用3个整数的数组:
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; for (int i = 0; i < MAX; i++) { cout << "Value of var[" << i << "] = "; cout << var[i] << endl; } return 0; }
当上述代码被编译和执行时,它产生了以下结果:
Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200
可能有一种情况,当我们要保持一个数组,它可以存储指针为int或char或任何其他可用的数据类型。下面是一个整数指针数组的声明:
int *ptr[MAX];
声明ptr为max整型指针数组。因此,每一个元素在ptr,现在拥有一个指向一个int值。下面的例子利用了将被存储在指针数组如下三个整数:
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr[MAX]; for (int i = 0; i < MAX; i++) { ptr[i] = &var[i]; // assign the address of integer. } for (int i = 0; i < MAX; i++) { cout << "Value of var[" << i << "] = "; cout << *ptr[i] << endl; } return 0; }
当上述代码被编译和执行时,它产生了以下结果:
Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200
还可以使用指针数组字符存储字符串列表如下:
#include <iostream> using namespace std; const int MAX = 4; int main () { char *names[MAX] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali", }; for (int i = 0; i < MAX; i++) { cout << "Value of names[" << i << "] = "; cout << names[i] << endl; } return 0; }
当上述代码被编译和执行时,它产生了以下结果:
Value of names[0] = Zara Ali Value of names[1] = Hina Ali Value of names[2] = Nuha Ali Value of names[3] = Sara Ali