二维数组如何作为函数参数使用?

转自:http://blog.csdn.net/xinshen1860/article/details/20620227

如果我们需要编写一个处理二维数组的函数,那么这个函数原型应该如何声明呢?


首先,我们应该牢记:数组名被视为其地址,因此,相应的形参是一个指针。例如,假设有如下的代码:


[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int data[3][4] = { {1, 2, 3, 4}, {5, 5, 7, 8}, {9, 10, 11, 12} }  
  2. int total = sum(data, 3);  
那么sun函数的原型应该如何声明呢?为什么将行数3作为参数,而不将列数4作为参数呢?


我们可以这样理解:data 是一个数组名,该数组有3个元素。而这3个元素本身都是又4个 int 组成的数组。因此 data 的类型是 指向由4个int组成的数组的指针。

因此正确的 sum 原型如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int sum( int (*arr) [4], int size);  
  2. //其中的括号是必不可少的,因为下面的声明将声明一个由四个指向int的指针组成的数组,而不是一个指向由4个int组成的数组的指针。  
  3.   
  4. int *arr[4];   //声明了一个指针数组,这个数组包含4个int指针变量  
  5. int (*arr)[4] //声明了一个指针变量,这个指针指向由4个int组成的数组  

还有另外一种声明格式,含义与上述正确原型完全相同,但是可读性更强:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int sum(int arr[][4], int size);  

上述2个原型都指出,arr 是指针而不是数组。还需要注意的是:int arr [ ] [4] 的含义就是: arr 是指向由4个 int 构成的数组的指针。因此,指针类型指定了列数,也就是说:函数形参已经确定了实参数组的列数,这就是为什么没有将列数作为独立的函数参数进行传递的原因


另外:sizeof只能用在指定大小,即栈中的数组计算大小,不能用于new出来的空间和外部数组:

首先看一MSDN上如何对sizeof进行定义的:

sizeof Operator
sizeof expression


The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type 
(including aggregate types). This keyword returns a value of type size_t.

The expression is either an identifier or a type-cast expression (a type specifier enclosed in 
parentheses).

When applied to a structure type or variable, sizeof returns the actual size, which may include 
padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof 
returns the size of the entire array. The sizeof operator cannot return the size of dynamically 
allocated arrays or external arrays.

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值