我可以将 int 数组传递给这两个函数(一维和二维数组)。它们之间有什么区别?对于第二个函数,您需要指定数组的大小。为什么?
void foo(int *a, int cols)
void bar(int (*a)[N])
我有一个程序,我想将 2d int 数组传递给函数。哪一个更好用,这重要吗?
最佳答案
对于二维矩阵,这些方法之间存在显着差异
- 在第一个方法中,您传递了一个指向
int
的指针,这不是矩阵的正确类型,即使在隐式衰减之后也是如此。 cols
在第一个原型(prototype)中是一个int
参数,而在第二个原型(prototype)中它是一个常量N
。在这两种情况下,行数均未指定,因此它必须是隐式的,因为它是常数,或者因为矩阵是方阵。- 在第一种情况下,您需要显式编写索引计算,而在第二种情况下,您可以使用
a[row][col]
,这将更简单、更具可读性并且编译效率更高代码。
请注意,自 C99 以来,还有第三种可能性,允许您使用数组语法,即使列数可变。这是一个例子:
#include <stdio.h>
#include <stdlib.h>
void init_matrix(int rows, int cols, int (*a)[cols]) {
int x = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
a[r][c] = x++;
}
}
}
void print_matrix(int rows, int cols, const int (*a)[cols]) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
printf("%3d%c", a[r][c], " \n"[c == cols - 1]);
}
}
}
int main() {
int cols = 4, rows = 3;
int (*a)[cols] = malloc(sizeof(*a) * rows);
init_matrix(rows, cols, a);
print_matrix(rows, cols, a);
return 0;
}
关于arrays - 函数中 int* a 和 int (*a)[N] 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74748967/