天天看點

C++ 指向數組的指針

如果您對 C++ 指針的概念有所了解,那麼就可以開始本章的學習。數組名是一個指向數組中第一個元素的常量指針。是以,在下面的聲明中:

double balance[50];      

balance 是一個指向 &balance[0] 的指針,即數組 balance 的第一個元素的位址。是以,下面的程式片段把 p 指派為 balance 的第一個元素的位址:

double *p;
double balance[10];

p = balance;      

使用數組名作為常量指針是合法的,反之亦然。是以,*(balance + 4) 是一種通路 balance[4] 資料的合法方式。

一旦您把第一個元素的位址存儲在 p 中,您就可以使用 *p、*(p+1)、*(p+2) 等來通路數組元素。下面的執行個體示範了上面讨論到的這些概念:

#include <iostream>
using namespace std;
 
int main ()
{
   // 帶有 5 個元素的整型數組
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;

   p = balance;
 
   // 輸出數組中每個元素的值
   cout << "使用指針的數組值 " << endl; 
   for ( int i = 0; i < 5; i++ )
   {
       cout << "*(p + " << i << ") : ";
       cout << *(p + i) << endl;
   }

   cout << "使用 balance 作為位址的數組值 " << endl;
   for ( int i = 0; i < 5; i++ )
   {
       cout << "*(balance + " << i << ") : ";
       cout << *(balance + i) << endl;
   }
 
   return 0;
}



#include <stdio.h>

int main ()
{
   /* 帶有 5 個元素的整型數組 */
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;
   int i;

   p = balance;
 
   /* 輸出數組中每個元素的值 */
   printf( "使用指針的數組值\n");
   for ( i = 0; i < 5; i++ )
   {
       printf("*(p + %d) : %f\n",  i, *(p + i) );
   }

   printf( "使用 balance 作為位址的數組值\n");
   for ( i = 0; i < 5; i++ )
   {
       printf("*(balance + %d) : %f\n",  i, *(balance + i) );
   }
 
   return 0;
}      

當上面的代碼被編譯和執行時,它會産生下列結果:

使用指針的數組值
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
使用 balance 作為位址的數組值
*(balance + 0) : 1000
*(balance + 1) : 2
*(balance + 2) : 3.4
*(balance + 3) : 17
*(balance + 4) : 50      

在上面的執行個體中,p 是一個指向 double 型的指針,這意味着它可以存儲一個 double 類型的變量。一旦我們有了 p 中的位址,*p 将給出存儲在 p 中相應位址的值,正如上面執行個體中所示範的。