【问题标题】:Return Struct from Function in C从 C 中的函数返回结构
【发布时间】:2013-11-05 18:31:42
【问题描述】:

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

然后我编译,没有错误...

我做了一些测试:

Main.c

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

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


编辑: 当我运行我的代码时,我有“.exe 已停止工作”..


我做错了什么?

【问题讨论】:

  • 你为什么认为有问题?
  • 对不起,我忘了最重要的!
  • ".exe 已停止工作" 你有没有抛出异常?如果是,那是什么?

标签: c struct dynamic-memory-allocation


【解决方案1】:

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));

您应该在所有警告都打开的情况下进行编译,并且在所有警告消失之前不要运行程序。

【讨论】:

    【解决方案2】:

    你声明CreateNewMatrix返回一个结构体:

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

    但是当你使用它时,你期望一个指向结构的指针:

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

    不过,这应该是编译器错误。

    【讨论】:

    • 我不知道为什么,但我将 CreateNewMatrix 的返回值从结构更改为指针,现在它工作正常!谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多