国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++數組作為函數參數的幾個問題

2019-11-06 06:17:57
字體:
來源:轉載
供稿:網友

本文需要解決C++中關于數組的2個問題:1. 數組作為函數參數,傳值還是傳址?2. 函數參數中的數組元素個數能否確定?

先看下面的代碼。

#include <iostream>    using namespace std;    void testArrayArg(int a[])  {    cout << endl;      cout << "in func..." << endl;    cout << "array address: " << a << endl;    cout << "array size: " << sizeof(a) << endl;    cout << "array element count: " << sizeof(a) / sizeof(a[0]) << endl;      cout << "changing the 4th element's value to 10." << endl;    a[3] = 10;  }    int main()  {    int a[] = {1, 2, 3, 4, 5};      cout << "in main..." << endl;    cout << "array address: " << a << endl;    cout << "array size: " << sizeof(a) << endl;    cout << "array element count: " << sizeof(a) / sizeof(a[0]) << endl;      testArrayArg(a);      cout << endl << "the 4th element's value: " << a[3] << endl;  return 0;  } 

運行結果如下:

 

in main...array address: 0012FF4Carray size: 20array element count: 5

 

in func...array address: 0012FF4Carray size: 4array element count: 1changing the 4th element's value to 10.

 

the 4th element's value: 10

 

當我們直接將數組a作為參數調用testArrayArg()時,實參與形參的地址均是0012FF4C。并且,在testArrayArg()中將a[3]的值修改為10后,返回main()函數中,a[3]的值也已經改變。這些都說明C++中數組作為函數參數是傳址。

 

特別需要注意的是,在main()中,數組的大小是可以確定的。

 

array size: 20array element count: 5

 

但作為函數參數傳遞后,其大小信息丟失,只剩下數組中第一個元素的信息。

array size: 4array element count: 1

 

這是因為C++實際上是將數組作為指針來傳遞,而該指針指向數組的第一個元素。至于后面數組在哪里結束,C++的函數傳遞機制并不負責。

 

上面的特性可總結為,數組僅在定義其的域范圍內可確定大小。

因此,如果在接受數組參數的函數中訪問數組的各個元素,需在定義數組的域范圍將數組大小作為另一輔助參數傳遞。則有另一函數定義如下:

[cpp] view plaincopyvoid testArrayArg2(int a[], int arrayLength)  {    cout << endl << "the last element in array is: " << a[arrayLength - 1] << endl;  }  

可在main()中這樣調用:

 

testArrayArg2(a, sizeof(a) / sizeof(a[0]));

 

這樣,testArrayArg2()中便可安全地訪問數組元素了。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 湖北省| 西吉县| 台南市| 曲阜市| 石狮市| 上栗县| 合江县| 昌邑市| 永春县| 云梦县| 晋江市| 临城县| 余姚市| 巴中市| 铜山县| 虎林市| 开化县| 九台市| 邵阳县| 湟中县| 马尔康县| 忻城县| 阜阳市| 罗定市| 浮山县| 长葛市| 黄陵县| 张掖市| 景东| 收藏| 昆山市| 龙南县| 邵阳县| 陆丰市| 安福县| 谢通门县| 天等县| 台东市| 河东区| 西藏| 繁昌县|