【发布时间】: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