我是 C 语言的新手,我需要进行大量矩阵计算,因此我决定使用矩阵结构。
矩阵.h
struct Matrix
{
unsigned int nbreColumns;
unsigned int nbreRows;
double** matrix;
};
struct Matrix CreateNewMatrix(unsigned int n,unsigned int m);
double GetMatrixValue(struct Matrix* m,unsigned int ligne,unsigned int colonne);
矩阵.c
#include "matrix.h"
struct Matrix CreateNewMatrix(unsigned int n,unsigned int m){
struct Matrix mat;
mat.nbreColumns = n;
mat.nbreRows = m;
mat.matrix = (double**)malloc(n * sizeof(double*));
unsigned int i;
for(i = 0; i < n; i++)
{
mat.matrix[i] = (double*)calloc(m,sizeof(double));
}
return mat;
}
double GetMatrixValue(struct Matrix* m,unsigned int ligne,unsigned int colonne){
return m->matrix[ligne][colonne];
}
然后我编译,没有报错...
我做了一些测试:
主要.c
struct Matrix* m1 = CreateNewMatrix(2,2);
printf("Valeur : %f",GetMatrixValue(m1,1,1));
编辑: 当我运行我的代码时,我有“.exe 已停止工作”..
我做错了什么?
最佳答案
CreateNewMatrix
返回一个 Matrix
而不是 Matrix*
struct Matrix* m1 = CreateNewMatrix(2,2);
printf("Valeur : %f",GetMatrixValue(m1,1,1));
应该是
struct Matrix m1 = CreateNewMatrix(2,2);
printf("Valeur : %f",GetMatrixValue(&m1,1,1));
您应该在打开所有警告的情况下进行编译,并且在所有警告消失之前不要运行程序。
关于c - 从 C 中的函数返回结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796156/