C++ 指針數(shù)組

C++ 指針 C++ 指針

在我們講解指針數(shù)組的概念之前,先讓我們來(lái)看一個(gè)實(shí)例,它用到了一個(gè)由 3 個(gè)整數(shù)組成的數(shù)組:

#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;
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

可能有一種情況,我們想要讓數(shù)組存儲(chǔ)指向 int 或 char 或其他數(shù)據(jù)類型的指針。下面是一個(gè)指向整數(shù)的指針數(shù)組的聲明:

int *ptr[MAX];

在這里,把 ptr 聲明為一個(gè)數(shù)組,由 MAX 個(gè)整數(shù)指針組成。因此,ptr 中的每個(gè)元素,都是一個(gè)指向 int 值的指針。下面的實(shí)例用到了三個(gè)整數(shù),它們將存儲(chǔ)在一個(gè)指針數(shù)組中,如下所示:

#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]; // 賦值為整數(shù)的地址
   }
   for (int i = 0; i < MAX; i++)
   {
      cout << "Value of var[" << i << "] = ";
      cout << *ptr[i] << endl;
   }
   return 0;
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

您也可以用一個(gè)指向字符的指針數(shù)組來(lái)存儲(chǔ)一個(gè)字符串列表,如下:

#include <iostream>
 
using namespace std;
const int MAX = 4;
 
int main ()
{
 const 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;
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

C++ 指針 C++ 指針