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


轉之:http://blog.csdn.net/tanghw/article/details/6554538

本文需要解決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: 0012FF4C
array size: 20
array element count: 5

 

in func...
array address: 0012FF4C
array size: 4
array element count: 1
changing 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: 20
array element count: 5

 

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

 

array size: 4
array element count: 1

 

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

 

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

 

void 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()中便可安全地訪問數組元素了。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM