c - 从 C 中的函数返回结构

标签 c struct dynamic-memory-allocation

我是 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/

相关文章:

c - 为什么编译器可以接受这个?

c - 为什么使用 typedef *after* 结构定义?

c - 唯一元素 - 结构数组

c++ - 在 MS Visual Studio 2013 中,我可以使用什么来代替 std::aligned_alloc?

c - 从 perf 获取用户空间堆栈信息

c - c中的堆栈内存布局

assembly - 内存寄存器如何用于保存不同的类型?

c++ - 如何找到继承类的分配地址

c - 如何从用户空间使用asm/system.h?

c - 如何用C语言设计嵌入式软件应用库接口(interface)的通用向后兼容API?