我为 gcc C11/C99 制作了一个基于链接的适当分配功能的解决方案:
http://c-faq.com/aryptr/dynmuldimary.html
http://c-faq.com/aryptr/ary2dfunc3.html
经过评论中的一些讨论,很明显 matrix2 被正确分配,它可以传递给这个函数 fn(int row, int col, int array[col][row]) 作为 matrix2[0] (一维数组中的数据) 转换为 (double (*)[])
//compile with gcc --std=c11 program.c
#include <stdio.h>
#include <stdlib.h>
#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<row; i++){
for(int j=0; j<column; j++)
matrix[i][j]=i+1;
}
}
void print_matrix(int row, int column, double matrix[row][column]){
for(int i=0; i<row; i++){
for(int j=0; j<column; j++)
printf("%.2lf ", matrix[i][j]);
printf("\n");
}
}
double **alloc_matrix2(int row, int column){
double **matrix;
matrix=malloc(row*sizeof(double*));
matrix[0] = (double *)malloc(row*column*sizeof(double));
for(int i = 1; i < row; i++)
matrix[i] = matrix[0]+i*column;
return matrix;
}
double *alloc_matrix3(int row, int column){
double *matrix;
matrix=malloc(row*column*sizeof(double));
return matrix;
}
void *alloc_matrix4(int row, int column){
double (*matrix)[column];
matrix = (double (*)[])malloc(row*sizeof(*matrix));
return matrix;
}