如何在C中的函数中传递二维数组(矩阵)?我需要这样做来保持矩阵上的操作。这是否意味着它需要以参考的方式通过?这样就够了吗?void operate_on_matrix(char matrix[][20]);
3 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
#define ROWS 4#define COLS 5void 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(ROWS, COLS, x);}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);}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*cols+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);}#include <stdio.h>#include <stdlib.h>#include <time.h>extern void func_vla(int rows, int cols, int array[rows][cols]);extern void get_rows_cols(int *rows, int *cols);extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);void func_vla(int rows, int cols, int array[rows][cols]){
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = (i + 1) * (j + 1);
}
}}int main(void){
int rows, cols;
get_rows_cols(&rows, &cols);
int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
/* error check omitted */
func_vla(rows, cols, array);
dump_array("After initialization", rows, cols, array);
free(array);
return 0;}void dump_array(const char *tag, int rows, int cols, int array[rows][cols]){
printf("%s (%dx%d):\n", tag, rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
printf("%4d", array[i][j]);
putchar('\n');
}}void get_rows_cols(int *rows, int *cols){
srand(time(0)); // Only acceptable because it is called once
*rows = 5 + rand() % 10;
*cols = 3 + rand() % 12;}srand()
慕容708150
TA贡献1831条经验 获得超4个赞
void myfunc(int arr[M][N]) { // M is optional, but N is required
..}int main() {
int somearr[M][N];
...
myfunc(somearr);
...}
LEATH
TA贡献1936条经验 获得超7个赞
最简单的方法:传递可变长度的二维阵列
void func(int row, int col, int* matrix){
int i, j;
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
}
printf("\n");
}}int main(){
int matrix[2][3] = { {1, 2, 3}, {7, 8, 9} };
func(2, 3, matrix[0]);
return 0;}- 3 回答
- 0 关注
- 954 浏览
添加回答
举报
0/150
提交
取消
