简体   繁体   中英

Return Struct from Function in C

I'm very new to langage C and I need to make a lot of matrix calculation and I decided to use a matrix struct.

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];
}

Then I compile, no errors ...

I made a few tests :

Main.c

struct Matrix* m1 = CreateNewMatrix(2,2);

printf("Valeur : %f",GetMatrixValue(m1,1,1));


When I run my code, I had ".exe has stop working" .. 当我运行我的代码时,我有“ .exe已停止工作” ..


CreateNewMatrix returns a Matrix not a Matrix*

struct Matrix* m1 = CreateNewMatrix(2,2);
printf("Valeur : %f",GetMatrixValue(m1,1,1));

should be

struct Matrix m1 = CreateNewMatrix(2,2);
printf("Valeur : %f",GetMatrixValue(&m1,1,1));

You should compile with all warnings on and not run the program until all the warnings go away.

You declare CreateNewMatrix to return a struct:

struct Matrix CreateNewMatrix(unsigned int n,unsigned int m){

But when you use it you expect a pointer to a struct:

struct Matrix* m1 = CreateNewMatrix(2,2);

This should be a compiler error, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM