C – 在函数中分配矩阵

我试图使用一个带有尺寸和三指针的函数来分配矩阵。 我已经分配了一个int **(设置为NULL),我将其地址作为函数的参数传递。 由于某种原因,这给了我一个mem访问冲突。

void allocateMatrix(int ***matrix, int row, int col) { int i; if((*matrix = (int**)malloc(row * sizeof(int*))) == NULL) { perror("There has been an error"); exit(EXIT_FAILURE); } for(i = 0; i < row; ++i) { if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL) { perror("There has been an error"); exit(EXIT_FAILURE); } } } /* main.c */ int** matrix = NULL; allocateMatrix(&matrix, MATRIX_ROW, MATRIX_COL); //error 

你需要改变

 if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL) 

 if(((*matrix)[i] = (int*)malloc(col * sizeof(int))) == NULL) // ^ ^ 

在使用数组下标之前,需要取消引用matrix
*matrix[i]相当于*(matrix[i])

这是运算符优先级的问题。 在

 if ((*matrix[i] = (int*)malloc( ... )) 

默认优先级是*(matrix[i]) ,而你应该使用(*matrix)[i]

我仍然建议将矩阵分配为连续数组,而不是指向数组的指针数组。

我已经为gcc C11 / C99制作了一个解决方案程序,并根据链接提供了适当的分配function:

http://c-faq.com/aryptr/dynmuldimary.html

http://c-faq.com/aryptr/ary2dfunc3.html

经过评论中的一些讨论,很明显矩阵2被正确分配,它可以作为matrix2 [0]传递给这个函数fn(int row,int col,int array [col] [row])(一维数组中的数据) )使用强制转换为(double(*)[])

 //compile with gcc --std=c11 program.c #include  #include  #define MX 9 #define MY 14 void input_matrix(int row, int column, double matrix[row][column]); void print_matrix(int row, int column, double matrix[row][column]); double **alloc_matrix2(int row, int column); double *alloc_matrix3(int row, int column); void *alloc_matrix4(int row, int column); int main() { int i=MX, j=MY; printf("Generate input values and print matrices with functions fn(int w, int k, double matrix[w][k]) (in C99 and C11)\n"); double matrix1[i][j]; input_matrix(MX,MY,matrix1); printf("matrix static\n"); print_matrix(MX,MY,matrix1); double **matrix2; //data of matrix2 is just matrix3 matrix2=alloc_matrix2(MX,MY); input_matrix(MX,MY,(double (*)[])(*matrix2)); printf("matrix two times allocated one for pointers, the second for data (double (*)[])(m[0])\n"); print_matrix(MX,MY,(double (*)[])(matrix2[0])); free(*matrix2); free(matrix2); double *matrix3=alloc_matrix3(MX,MY); input_matrix(MX,MY,(double (*)[])matrix3); printf("matrix allocated as two-dimensional array\n"); print_matrix(MX,MY,(double (*)[])matrix3); free(matrix3); j=MY; double (*matrix4)[j]; matrix4 = (double (*)[])alloc_matrix4(MX,MY); input_matrix(MX,MY,matrix4); printf("matrix allocated via pointer to array m = (double (*)[])malloc(MX * sizeof(*m))\n"); print_matrix(MX,MY,matrix4); free(matrix4); printf("\nThe End!\n"); return 0; } void input_matrix(int row, int column, double matrix[row][column]){ for(int i=0; i