如何通过二维数组(矩阵)在C中的函数? [英] How to pass 2D array (matrix) in a function in C?
问题描述
我需要这样做坚持的矩阵运算以及。这是否意味着,它需要通过引用传递?
I need to do this to persist operations on the matrix as well. Does that mean that it needs to be passed by reference?
请问这个就够了?
无效operate_on_matrix(字符矩阵[] [20]);
推荐答案
C不真有多维数组,但有几种方法来模拟他们。以这种阵列传递给函数的方式取决于用于模拟多个维度的方式:
C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:
1)使用数组的数组。这只能使用,如果你的数组边界在编译时完全确定,或者如果你的编译器支持 VLA的
1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:
#define ROWS 4
#define COLS 5
void func(int array[ROWS][COLS])
{
int i, j;
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
array[i][j] = i*j;
}
}
}
void func_vla(int rows, int cols, int array[rows][cols])
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int x[ROWS][COLS];
func(x);
func_vla(x, rows, cols);
}
2)用一个指针(动态分配)数组(动态分配)阵列。这主要是用来当数组边界是不知道,直到运行时。
2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.
void func(int** array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int rows, cols, i;
int **x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * sizeof *x);
for (i=0; i<rows; i++)
{
x[i] = malloc(cols * sizeof *x[i]);
}
/* use the array */
func(x, rows, cols);
/* deallocate the array */
for (i=0; i<rows; i++)
{
free(x[i]);
}
free(x);
}
3)使用1维阵列和修正内容的索引。这可以与静态分配(固定大小)被使用和动态分配数组:
3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:
void func(int* array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i*rows+j] = i*j;
}
}
}
int main()
{
int rows, cols;
int *x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * cols * sizeof *x);
/* use the array */
func(x, rows, cols);
/* deallocate the array */
free(x);
}
这篇关于如何通过二维数组(矩阵)在C中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!