繁体   English   中英

使用结构并在C中返回2d数组

[英]working with structs and returning 2d arrays in C

我遇到一些麻烦,找到返回带有数组或指针数组的结构的最佳方法。

这是我想要做的:我有一个结构

typedef struct {
    double *matrix;
    int cols;
    int rows;
    int nelems;
} ResultMat;

以及解析文件的函数。 我需要调用该函数并让它返回结构

ResultMat read (string file, string tag) {

  ResultMat mat;

  .....
  mat.cols = //some value from the file
  mat.rows = //some value from the file


  double array[rows][cols];
  //now i fill the array

  .......
  mat.matrix = *array;

  return mat;
}

在一个数组中填充了值,我想用mat.matrix中存储的数组的数组/指针返回整个结构。

怎么做,是否有更好的方法? 我是C的新手,更熟悉OO编程,这就是为什么我无法找到最佳解决方案。

希望有人能给我一些帮助! 谢谢

我认为double array[rows][cols]; 将在本地函数堆栈上创建数组时出现问题。 离开功能后,这将被删除。 您还应该注意,可变长度数组不符合ANSI-C,在我看来最好不要使用它。

您应该使用指针和动态内存分配。 malloc将是这里的关键字。

希望这可以帮助

我能想到的另一种方法是将所有输出参数作为输入指针,以便你的原型函数看起来像这样:

void read (string file, string tag, double *matrix, int *cols, int *rows, int *nelms);

或者你可以保留结构,并采取这样的方式:

void read (string file, string tag, ResultMat *myStructure);

IMO,没有“更好的方式”,这些都只是不同的选择,你的是另一种选择,我发现自己经常使用。

暂无
暂无

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

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