本文需要解決C++中關(guān)于數(shù)組的2個問題:1. 數(shù)組作為函數(shù)參數(shù),傳值還是傳址?2. 函數(shù)參數(shù)中的數(shù)組元素個數(shù)能否確定?
先看下面的代碼。
#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; }運行結(jié)果如下:
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
當(dāng)我們直接將數(shù)組a作為參數(shù)調(diào)用testArrayArg()時,實參與形參的地址均是0012FF4C。并且,在testArrayArg()中將a[3]的值修改為10后,返回main()函數(shù)中,a[3]的值也已經(jīng)改變。這些都說明C++中數(shù)組作為函數(shù)參數(shù)是傳址。
特別需要注意的是,在main()中,數(shù)組的大小是可以確定的。
array size: 20array element count: 5
但作為函數(shù)參數(shù)傳遞后,其大小信息丟失,只剩下數(shù)組中第一個元素的信息。
array size: 4array element count: 1
這是因為C++實際上是將數(shù)組作為指針來傳遞,而該指針指向數(shù)組的第一個元素。至于后面數(shù)組在哪里結(jié)束,C++的函數(shù)傳遞機制并不負責(zé)。
上面的特性可總結(jié)為,數(shù)組僅在定義其的域范圍內(nèi)可確定大小。
因此,如果在接受數(shù)組參數(shù)的函數(shù)中訪問數(shù)組的各個元素,需在定義數(shù)組的域范圍將數(shù)組大小作為另一輔助參數(shù)傳遞。則有另一函數(shù)定義如下:
[cpp] view plaincopyvoid testArrayArg2(int a[], int arrayLength) { cout << endl << "the last element in array is: " << a[arrayLength - 1] << endl; }可在main()中這樣調(diào)用:
testArrayArg2(a, sizeof(a) / sizeof(a[0]));
這樣,testArrayArg2()中便可安全地訪問數(shù)組元素了。
新聞熱點
疑難解答
圖片精選