将静态分配的二维数组作为 C 中的函数参数传递 [英] passing statically allocated 2D arrays as function arguments in C
问题描述
考虑这个代码:
<预><代码>#include这按预期工作正常.
现在,我想在一个单独的源文件中编写处理二维矩阵的函数,并在需要的地方链接它们.
但是后来我遇到了一个问题,如函数printMatrix
,matrix
指向的int
数组的大小(即N
) 在编译时是必需的.因此,当大小不同时,我的函数在其他情况下将不起作用.
那么,我该如何处理?
动态数组是一种解决方案,但我想知道是否可以使用静态数组来完成.
如果在编译时不知道两种大小,则不能使用内置的 2D 数组类型.内置二维数组必须至少具有编译时已知的两种大小之一.
如果两个大小都是运行时值,那么您别无选择,只能使用二维数组的手动"实现,例如指向数组的指针数组.在这种情况下,函数声明可能如下所示(两种替代的等效形式)
void printMatrix(int *const *matrix, int n, int m);void printMatrix(int *const matrix[], int n, int m);
要访问数组元素,您仍然可以使用传统"语法
matrix[i][j]
数组本身将按如下方式创建(一个简单的例子)
int row0[] = { 1, 2, 3 };int row1[] = { 4, 5, 6 };int *矩阵[2];矩阵[0] = row0;矩阵[1] = row1;打印矩阵(矩阵, 2, 3);
但是如果您已经将矩阵实现为内置的二维数组
int matrix[2][3] = { ... };
然后为了能够将其传递给上述函数,您可以使用额外的临时行指针"数组将其转换"为上述形式
int *rows[2];行[0] = 矩阵[0];行[1] = 矩阵[1];打印矩阵(行,2, 3);
Consider this code:
#include <stdio.h>
#define N 5
void printMatrix(int (*matrix)[N],int n)
{
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%d",matrix[i][j]);
printf("\n");
}
}
int main()
{
int R[N][N]={{1,2,3},{4,5,6},{7,8,9}};
printMatrix(R,3);
}
This works fine as expected.
Now, I thought to write the functions handling 2D-matrices in a separate source file and link them wherever required.
But then I ran into a problem as in the function printMatrix
, the size of array of int
to which matrix
points (i.e N
) is required at compile-time. So, my functions would not work in other cases when the size is different.
So,How can I handle this?
Dynamic Arrays are a solution but i want to know if it can be done with static arrays.
You can't use the built-in 2D array type if both sizes are not known at compile time. A built-in 2D array must have at least one of the two sizes known at compile time.
If both sizes are run-time values, then you have no other choice but to use a "manual" implementation of 2D array, like an array of pointers to arrays, for example. In that case the function declaration might look as follows (two alternative equivalent forms)
void printMatrix(int *const *matrix, int n, int m);
void printMatrix(int *const matrix[], int n, int m);
To access to the array elements you can still use the "traditional" syntax
matrix[i][j]
The array itself would be created as follows (a simple example)
int row0[] = { 1, 2, 3 };
int row1[] = { 4, 5, 6 };
int *matrix[2];
matrix[0] = row0;
matrix[1] = row1;
printMatrix(matrix, 2, 3);
But if you already have a matrix implemented as a built-in 2d array
int matrix[2][3] = { ... };
then just to be able to pass it to the above function you can "convert" it into the above form by using an additional temporary "row pointer" array
int *rows[2];
rows[0] = matrix[0];
rows[1] = matrix[1];
printMatrix(rows, 2, 3);
这篇关于将静态分配的二维数组作为 C 中的函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!