为什么传递给函数的二维数组需要它的大小? [英] Why does 2 dimension array passing to function requires its size?

查看:28
本文介绍了为什么传递给函数的二维数组需要它的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启发了这个问题.

为什么 -

void display(int p[][SIZE]) // allowed

void display(int p[][]) // not allowed

?

推荐答案

因为数组在传递给函数时衰减到指针.如果不提供数组第二维的基数,编译器将不知道如何解引用这个指针.

Because arrays decay to pointers when passed to a function. If you do not provide the cardinality of the second dimension of the array, the compiler would not know how to dereference this pointer.

这里有一个更长的解释:当你写这个

Here is a longer explanation: when you write this

p[index]

编译器执行一些指针运算来找到它需要引用的元素的地址:它将index乘以p元素的大小,然后加上到p的基地址:

the compiler performs some pointer arithmetic to find the address of the element that it needs to reference: it multiplies index by the size of p's element, and adds it to the base address of p:

address = <base address of p> + index * <size of p's element>

当您尝试传递这样的数组时,p[][],编译器只知道 p 的基地址,而不知道其元素的大小.为了让编译器知道 p 元素的大小,您需要提供第二维的基数.

When you try passing an array like this, p[][], the compiler knows only the base address of p, but not the size of its element. It is in order for the compiler to know the size of p's element that you need to provide the cardinality of the second dimension.

这篇关于为什么传递给函数的二维数组需要它的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆