使用指標訪問陣列元素的 C++ 程式


指標儲存變數的記憶體位置或地址。換句話說,指標引用記憶體位置,獲取儲存在該記憶體位置的值稱為指標的解引用。

一個使用指標訪問陣列單個元素的程式如下所示:

示例

 即時演示

#include <iostream>
using namespace std;
int main() {
   int arr[5] = {5, 2, 9, 4, 1};
   int *ptr = &arr[2];
   cout<<"The value in the second index of the array is: "<< *ptr;
   return 0;
}

輸出

The value in the second index of the array is: 9

在上面的程式中,指標 ptr 儲存陣列中第三個索引(即 9)的元素的地址。

這在以下程式碼片段中顯示。

int *ptr = &arr[2];

指標被解引用,並且使用間接運算子 (*) 顯示值 9。這在如下所示。

cout<<"The value in the second index of the array is: "<< *ptr;

另一個程式,其中使用單個指標訪問陣列的所有元素,如下所示。

示例

 即時演示

#include <iostream>
using namespace std;
int main() {
   int arr[5] = {1, 2, 3, 4, 5};
   int *ptr = &arr[0];
   cout<<"The values in the array are: ";
   for(int i = 0; i < 5; i++) {
      cout<< *ptr <<" ";
      ptr++;
   }
   return 0;
}

輸出

The values in the array are: 1 2 3 4 5

在上面的程式中,指標 ptr 儲存陣列第一個元素的地址。這是如下完成的。

int *ptr = &arr[0];

在此之後,使用 for 迴圈來解引用指標並列印陣列中的所有元素。在迴圈的每次迭代中,指標都會遞增,即在每次迴圈迭代中,指標都指向陣列的下一個元素。然後列印該陣列值。這可以在以下程式碼片段中看到。

for(int i = 0; i < 5; i++) {
   cout<< *ptr <<" ";
   ptr++;
}

更新於: 2020年6月24日

13K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.