C++数组作为函数参数的几个问题

来源:互联网 发布:windows 会员如何加入 编辑:程序博客网 时间:2024/04/27 23:58

本文需要解决C++中关于数组的2个问题:
1. 数组作为函数参数,传值还是传址?
2. 函数参数中的数组元素个数能否确定?


先看下面的代码。

 

[cpp] view plaincopy
  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. void testArrayArg(int a[])  
  6. {  
  7.   cout << endl;  
  8.   
  9.   cout << "in func..." << endl;  
  10.   cout << "array address: " << a << endl;  
  11.   cout << "array size: " << sizeof(a) << endl;  
  12.   cout << "array element count: " << sizeof(a) / sizeof(a[0]) << endl;  
  13.   
  14.   cout << "changing the 4th element's value to 10." << endl;  
  15.   a[3] = 10;  
  16. }  
  17.   
  18. int main()  
  19. {  
  20.   int a[] = {1, 2, 3, 4, 5};  
  21.   
  22.   cout << "in main..." << endl;  
  23.   cout << "array address: " << a << endl;  
  24.   cout << "array size: " << sizeof(a) << endl;  
  25.   cout << "array element count: " << sizeof(a) / sizeof(a[0]) << endl;  
  26.   
  27.   testArrayArg(a);  
  28.   
  29.   cout << endl << "the 4th element's value: " << a[3] << endl;  
  30.   
  31.   return 0;  
  32. }  


 

运行结果如下:

 

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++的函数传递机制并不负责。

 

上面的特性可总结为,数组仅在定义其的域范围内可确定大小

 

因此,如果在接受数组参数的函数中访问数组的各个元素,需在定义数组的域范围将数组大小作为另一辅助参数传递。则有另一函数定义如下:

[cpp] view plaincopy
  1. void testArrayArg2(int a[], int arrayLength)  
  2. {  
  3.   cout << endl << "the last element in array is: " << a[arrayLength - 1] << endl;  
  4. }  

可在main()中这样调用:

 

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

 

这样,testArrayArg2()中便可安全地访问数组元素了。

0 0
原创粉丝点击