C++指針數組
之前我們理解指針數組概念,讓我們考慮下麵的例子,這使得使用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