当二维数组和多维数组作为C语言函数参数 [英] When two-dimensional array and multidimensional array as function parameters in C language
问题描述
可能重复:结果
如何使用数组在C ++?
一维数组作为函数参数:
One dimensional array as a function parameter:
#include <stdio.h>
#include <string.h>
int func(int a[], int n)
{
int i;
for(i = 0; i < n; i++)
printf("%d ", a[i][j]);
}
int main(void)
{
int a[2] = {1,2};
func(a, 2);
}
它编译并运行正常。
it compiles and runs correctly.
但是,当一个二维阵列作为函数参数:
But when a two-dimensional array as a function parameter:
#include <stdio.h>
#include <string.h>
int func(int a[][], int n)
{
int i, j;
for(i = 0; i < n; i++)
for(j = 0 ; j < n; j++)
printf("%d ", a[i][j]);
printf("\n");
}
int main(void)
{
int a[2][2] = {{1,2}, {3,4}};
func(a, 2);
}
它不能正确编译。我必须修改code是这样的:
it can not compile correctly. I must modify the code like this:
#include <stdio.h>
#include <string.h>
int func(int a[][2], int n)
{
int i, j;
for(i = 0; i < n; i++)
for(j = 0 ; j < n; j++)
printf("%d ", a[i][j]);
printf("\n");
}
int main(void)
{
int a[2][2] = {{1,2}, {3,4}};
func(a, 2);
}
我不知道为什么?任何人都可以解释它如何工作?非常感谢。
I do not know why? Anybody can explain how it works? Many thanks.
推荐答案
阵列(两者之一,多维c)中驻留在连续的内存块。这意味着,当你定义字符一个[3]
,该数组在内存布局是这样的(原谅我的可怕的ASCII艺术技能):
Arrays (both one and multidimensional) in c reside in continuous memory blocks. This means that when you define char a[3]
, the array is laid out in memory like this (forgive my terrible ascii art skills):
| a[0] | a[1] | a[2] |
对于一个二维数组一个烧焦[2] [3]
,布局是这样的:
| a[0][0] | a[0][1] | a[0][2] | a[1][0] | a[1][1] | a[1][2] |
^
+--- first row ends here
因此,当您索引到一个二维数组 A [I] [J]
,编译器生成code等价于:
Therefore, when you index into a two-dimensional array a[i][j]
, the compiler generates code equivalent to this:
*(a + i*3 + j)
这可以理解为跳过我行采取行小区j。要做到这一点,编译器必须知道该行的长度(这是第二维)。这意味着,第二个维度是类型定义的一部分!
Which can be read as "skip i rows and take cell j in that row". To accomplish this, the compiler must know the length of the row (which is the second dimension). This means that the second dimension is a part of the type definition!
因此,当你想传递一个二维数组到一个函数,你必须指定类型定义所需要的尺寸。
As such when you want pass a 2d array into a function, you must specify the needed dimension for the type definition.
这篇关于当二维数组和多维数组作为C语言函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!