我对C中的数组有一个非常基本的问题。 我有这个结构:
struct Matrix{
int rows;
int cols;
int** matrix;
};
当我尝试使用这个结构并声明一个Matrix时,我遇到了这个问题
Matrix matrix;
matrix->matrix = (int**) malloc(3*sizeof(int*));//allocates pointer to a pointers array
for (int i = 0; i <3; i++){
matrix->matrix[i] = (int*) malloc(3*sizeof(int));
}//allocating a 3X3 array
matrix->matrix={1,2,3,4,5,6,7,8,9};
然而最后一行不起作用,显然是因为编译器不理解我的数组的大小。
即使我尝试这样做:
matrix->matrix={{1,2,3},{4,5,6},{7,8,9}};
有谁知道怎么做?在我看来,这很简单。 非常感谢!
答案 0 :(得分:2)
您尝试应用的初始化类型仅在声明时有效。
例如:
int array[9] = {1,2,3,4,5,6,7,8,9};
int table[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
您可以按如下方式初始化矩阵:
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
matrix->matrix[i][j] = i*3+j+1;
答案 1 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
typedef struct Matrix{
int rows;
int cols;
int** matrix;
} Matrix;
Matrix *Create_Matrix(int rows, int cols, const int *values){
Matrix *matrix;
matrix = malloc(sizeof(Matrix));
matrix->rows = rows;
matrix->cols = cols;
matrix->matrix = malloc(rows * sizeof(int*));
for(int i=0; i < rows ;++i){
matrix->matrix[i] = malloc(cols * sizeof(int));
for(int j=0;j < cols; ++j)
matrix->matrix[i][j] = *values++;
}
return matrix;
}
int main(){
Matrix *m = Create_Matrix(3, 3, (int[]){1,2,3,4,5,6,7,8,9});
for(int r=0;r<3;++r){
for(int c=0;c<3;++c)
printf("%d ", m->matrix[r][c]);
printf("\n");
}
return 0;
}