C 語言中關於通過形參傳遞數組的長度計算的一些思考

  • 2019 年 11 月 22 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/solaraceboy/article/details/103187291

C 語言中關於通過形參傳遞數組的長度計算的一些思考

一 背景

學習 C 語言的過程中,計算數組的長度經常會碰到。在字元型的數組中我們可以使用 strlen() 來獲取當前數組的長度,對於其他類型的數組,這個方法就不適用了。由於經常會遇到計算數組長度的問題,經過思考,考慮通過一個函數來實現數組長度的計算。思路是這樣的:通過形參將數組傳遞給長度計算函數,長度計算函數計算完成之後返回數組長度。但是在實際實踐過程中遇到了問題,請繼續往下看!

二 實現程式碼

根據以上構想,寫了如下一段 demo:

# include<stdio.h>    int main(int argc, char * argv[])  {    int a[] = {2, 6, 3, 5, 9};  //  int length(int *);    int length(int []);    printf("The length of this array is: %dn",length(a));    printf("The length of this array is: %dn",sizeof a /sizeof a[0]);    return 0;  }    // int length(int *a)  int length(int a[])  {    int length;    length =  sizeof a / sizeof a[0];    return length;  }

執行結果:

The length of this array is: 2  The length of this array is: 5

三 結果分析及總結

  • 3.1 第一個結果,通過形參傳遞給數組長度計算函數來計算數組長度,得到的結果是: 2。很明顯,這是一個錯誤的結果。
  • 3.2 第二個結果,直接計算數組長度,符合預期。
  • 3.3 通過查閱相關資料,得出以下結論:

a[] 是長度計算的形式參數,在 main)() 函數中調用時,a 是一個指向數組第一個元素的指針。在執行 main() 函數時,不知道 a 所表示的地址有多大的數據存儲空間,只是告訴函數:一個數據存儲空間首地址。

sizoef a 的結果是指針變數 a 占記憶體的大小,一般在 64 位機上是8個位元組。a[0] 是 int 類型,sizeof a[0] 是4個位元組,結果是2。為此,我們再來看一下下面一段程式碼:

# include<stdio.h>      int main(int argc, char * argv[])  {    int a[] = {2, 6, 3, 5, 9};  //  int length(int *);    int length(int []);    int *p;    p = a;    printf("The length of this array is: %dn", length(a));    printf("The length of this array is: %dn", sizeof a /sizeof a[0]);    printf("The length of this pointer is: %dn", sizeof p);    return 0;  }    // int length(int *a)  int length(int a[])  {    int length;    length =  sizeof a / sizeof a[0];    return length;  }

執行結果:

The length of this array is: 2  The length of this array is: 5  The length of this pointer is: 8