如何正确定义函数返回的结构?

时间:2013-10-15 19:45:34

标签: c arrays function pointers structure

我正在尝试创建一个为“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);
}

3 个答案:

答案 0 :(得分:2)

以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(复杂)而不是sizeof(complex *),myfunction()的声明不包含关键字“struct”,并且没有对malloc()进行强制转换 - 它没有'需要一个并且可以隐藏您可能缺少包含其原型的包含文件的事实(请参阅Do I cast the result of malloc?)。 myfunction()实际上可以简化为一行:

return malloc(n*sizeof(complex));

答案 1 :(得分:1)

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

答案 2 :(得分:1)

这是一个编译得很好的代码:

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);
}
相关问题