C語言中指向陣列的指標



陣列名是指向陣列第一個元素的常量指標。因此,在此宣告中,

int balance[5];

balance 是指向 &balance[0] 的指標,也就是陣列第一個元素的地址。

示例

在此程式碼中,我們有一個指標 ptr,它指向名為 balance 的整數陣列的第一個元素的地址。

#include <stdio.h>

int main(){

   int *ptr;
   int balance[5] = {1, 2, 3, 4, 5};

   ptr = balance;

   printf("Pointer 'ptr' points to the address: %d", ptr);
   printf("\nAddress of the first element: %d", balance);
   printf("\nAddress of the first element: %d", &balance[0]);

   return 0;
}

輸出

在這三種情況下,您都會得到相同的輸出:

Pointer 'ptr' points to the address: 647772240
Address of the first element: 647772240
Address of the first element: 647772240

如果您獲取儲存在ptr指向的地址處的值,即*ptr,則它將返回1

陣列名作為常量指標

使用陣列名作為常量指標反之亦然是合法的。因此,*(balance + 4) 是訪問balance[4]處資料的合法方法。

一旦您將第一個元素的地址儲存在“ptr”中,就可以使用*ptr*(ptr + 1)*(ptr + 2) 等訪問陣列元素。

示例

以下示例演示了上面討論的所有概念:

#include <stdio.h>

int main(){

   /* an array with 5 elements */
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *ptr;
   int i;

   ptr = balance;
 
   /* output each array element's value */
   printf("Array values using pointer: \n");
	
   for(i = 0; i < 5; i++){
      printf("*(ptr + %d): %f\n",  i, *(ptr + i));
   }

   printf("\nArray values using balance as address:\n");
	
   for(i = 0; i < 5; i++){
      printf("*(balance + %d): %f\n",  i, *(balance + i));
   }
 
   return 0;
}

輸出

執行此程式碼時,將產生以下輸出:

Array values using pointer:
*(ptr + 0): 1000.000000
*(ptr + 1): 2.000000
*(ptr + 2): 3.400000
*(ptr + 3): 17.000000
*(ptr + 4): 50.000000

Array values using balance as address:
*(balance + 0): 1000.000000
*(balance + 1): 2.000000
*(balance + 2): 3.400000
*(balance + 3): 17.000000
*(balance + 4): 50.000000

在上面的示例中,ptr是一個可以儲存double型別變數地址的指標。一旦我們在ptr中有了地址,*ptr將給我們提供儲存在ptr中地址的值。

廣告