C++ 传递数组的问题

转自http://blog.csdn.net/tanghw/article/details/6554538

http://blog.csdn.net/wdqbupt/article/details/6858676 可以看看学学C++基础



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


先看下面的代码。

[cpp]  view plain copy
  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 plain copy
  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值