简体   繁体   English

从C函数返回结构

[英]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. 我是C语言的新手,我需要进行大量的矩阵计算,因此决定使用矩阵结构。

Matrix.h 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 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 MAIN.C

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

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


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


What did i do wrong ? 我做错了什么 ?

CreateNewMatrix returns a Matrix not a Matrix* CreateNewMatrix返回一个Matrix而不是一个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: 您声明CreateNewMatrix返回一个结构:

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. 但是,这应该是编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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