[英]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.