【问题标题】:How can I properly define a structure which is returned by a function?如何正确定义函数返回的结构?
【发布时间】:2013-10-15 19:45:33
【问题描述】:

我正在尝试创建一个函数,它为“main”中定义的结构数组分配内存。问题似乎是我的函数无法识别结构。以下代码有什么问题?

#include <math.h>
#include <stdio.h>
#include <stdlib.h>   

typedef struct typecomplex { float r; float i;  } complex;
complex *myfunction(int n);

int main (int argc, char *argv[]) {
    complex *result = myfunction(1000);
    exit(0);
}

...在另一个文件中...

struct complex *myfunction(int n)  {
  complex *result = (complex *)malloc(n*sizeof(*complex));
  if(result==NULL) return(NULL);
      else return(result);
}

【问题讨论】:

  • 您的struct 称为_complex。你为什么要搞那些肮脏的typedefs?此外,在这种情况下,您应该将 struct's 定义移动到 *.h 文件,以便从两个 *.c 文件中包含。
  • error: ‘complex’ undeclared (第一次在这个函数中使用)
  • 必须将声明放在一个通用头文件中...(并且请不要转换malloc()的返回值!并且不要弄乱保留的命名空间(即不要使用以下划线开头的标识符)等等等等
  • @H2CO3 - 不使用头文件的任何方法?
  • @JWDN 您可以复制定义,但最好使用头文件,这样定义就不会同时出现在两个地方;任何时候你这样做,你都可能犯一个错误,你更新了一个而忘记更新另一个。为什么不想使用头文件?

标签: c arrays function pointers structure


【解决方案1】:

基于 fvdalcin 的回答:

myprog.c:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>   
#include "mycomplex.h"


int main (int argc, char *argv[]) {
    complex *result = myfunction(1000);
    exit(0);
}

mycomplex.h:

#ifndef __MYCOMPLEX_H__
typedef struct typecomplex { float r; float i;  } complex;
complex *myfunction(int n);
#define __MYCOMPLEX_H__
#endif

(#ifdef 是一个好主意,可以防止它被多次包含。)

mycomplex.c:

#include <stdlib.h>
#include "mycomplex.h"

complex *myfunction(int n)  {
  complex *result = malloc(n*sizeof(complex));
  if(result==NULL) return(NULL);
      else return(result);
}

注意这里微妙但重要的修复——sizeof(complex) 代替 sizeof(complex*),myfunction() 的声明不包含关键字“struct”,并且没有对 malloc() 进行强制转换——它没有不需要,并且可以隐藏您可能缺少包含文件及其原型的事实(请参阅Do I cast the result of malloc?)。 myfunction() 实际上可以简化为一行:

return malloc(n*sizeof(complex));

【讨论】:

    【解决方案2】:

    将此声明typedef struct _complex { float r; float i; } complex; 移至“其他”文件。这个其他文件必须是你的 foo.h 文件,它有一个等效的 foo.c 实现在 foo.h 中声明的方法.然后您可以简单地将 foo.h 添加到您的 main.c 文件中,一切都会正常工作。

    【讨论】:

      【解决方案3】:

      这是一个编译良好的修正代码:

      typedef struct typecomplex { float r; float i;  } complex;
      complex *myfunction(int n)  {          
        complex *result = (complex *)malloc(n*sizeof(complex)); //removed * from sizeof(*complex)
        if(result==NULL) return(NULL);
            else return(result);
      }
      
      int main (int argc, char *argv[]) {
          complex *result = myfunction(1000);
          exit(0);
      }
      

      【讨论】:

      • 感谢您收看 *.这会起作用,但我需要将函数放在一个单独的文件中,所以很多程序都可以调用它:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-10-16
      相关资源
      最近更新 更多