【发布时间】:2013-06-19 01:32:36
【问题描述】:
我正在尝试将二维数组传递给函数。 我没有麻烦将它传递给函数。但是我很难理解这背后的逻辑。 函数和主要定义是这样的:
// Function to print the two-dimensional array
void print(int x, int y, int a[x][y]){
printf("\n");
int i, j;
for(i = 0; i < x; i++){
for(j = 0; j < y; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}
// Function to initialize the two-dimensional array
void init_2d(int *a, int x, int y){
int i, j;
for(i = 0; i < x; i++){
for(j = 0; j < y; j++){
a[i*y + j] = i + j;
}
printf("\n");
}
}
int main(){
int m = 2, n = 3;
int a[m][n]; // a two dimensional whose size has been defined using m and n
init_2d(a, m, n);
print(m, n, a);
}
具有讽刺意味的是,一切都运行良好。这是我的问题,因为我无法消化它的逻辑。
主要问题有:
- 我在书中读到的是,二维数组的大小应该使用常量或符号常量来定义。在我的主要内容中,我使用变量
m和n定义二维数组,但它工作正常。为什么? - 我还被告知通过将二维数组衰减为一维数组(通过在函数中将其定义为指向 int 的指针)来传递二维数组,即我在函数
init_2d中所做的方式。但在print函数中,我使用的是一个二维数组,其大小已使用变量x和y定义。这样做可以吗? - 是否也可以使用指向指针的指针来遍历二维数组?
任何人都可以建议我阅读有关此主题的好书,以清除我的所有概念吗?
我正在使用 codeblocks 来编译我的代码,编译器是 GNU GCC Compiler。
【问题讨论】:
-
2 很奇怪 - 我很惊讶它编译了!
-
@John3136 C99 支持前向参数声明。
-
@Armin:什么是“前向参数声明”,它与 John3136 的评论有何关系?
-
@AndreyT 什么是“前向参数声明”:
void print(int x, int y, int a[x][y])并连接到 VLA。 gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Variable-Length.html 我从其他地方得到了关键字。