将2D数组传递给函数并在c语言中编译时获得不兼容的指针类型



嗨,我有一个超级简单的代码下面创建一个随机的2D矩阵基于用户输入的行和列的数量。然而,每当我编译代码时,我都会得到错误消息:

test1.c:27:29: warning: passing argument 3 of ‘print_array’ from incompatible pointer type [-Wincompatible-pointer-types]
27 |     print_array(rows, cols, A);
|                             ^
|                             |
|                             double (*)[(sizetype)(cols)]
test1.c:7:46: note: expected ‘double *’ but argument is of type ‘double (*)[(sizetype)(cols)]’
7 | void print_array(int rows, int cols, double *A);

加上代码:

#include <stdio.h>
#include <stdlib.h>

#define MAX_VALS 2123
void print_array(int rows, int cols, double *A);
int main(){
int cols, rows, n = 0;
printf("Enter number of columns: n");
scanf("%d", &cols);
printf("Enter number of rows: n");
scanf("%d", &rows);
double A[rows][cols];
for(int m=0;m<rows;m++){
for(int n=0;n<cols;n++){
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%fn",m,n,A[m][n]);
}
}
print_array(rows, cols, A);
return 0;
}
void
print_array(int rows, int cols, double *A){
printf("n");
int m,n;
for (m=0;m<rows;m++){
for (n=0;n<cols;n++){
printf("A[%d,%d]=%fn",m,n,A[m*cols+n]);
}
}
}

这样调用print_array():

print_array(rows, cols, A[0]);

print_array(rows, cols, (double *)A);

相关内容

最新更新