1

I am trying to create a function which allocates memory for a structure array defined in "main". The problem seems to be that my function does not recognize the structure. What is wrong with the following code?

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

... and in another file...

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

3 回答 3

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

我的复杂.h:

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

(#ifdef 是防止它被多次包含的好主意。)

我的复杂.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));
于 2013-10-15T20:50:52.007 回答
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);
}
于 2013-10-15T19:59:44.923 回答
1

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

于 2013-10-15T19:53:47.997 回答