[英]Return Struct from Function in C
我是C语言的新手,我需要进行大量的矩阵计算,因此决定使用矩阵结构。
Matrix.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);
Matrix.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];
}
然后我编译,没有错误...
我做了一些测试:
MAIN.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));
您应该编译所有警告,并且在所有警告消失之前不要运行程序。
您声明CreateNewMatrix
返回一个结构:
struct Matrix CreateNewMatrix(unsigned int n,unsigned int m){
但是当您使用它时,您会期望指向结构的指针:
struct Matrix* m1 = CreateNewMatrix(2,2);
但是,这应该是编译器错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.