[英]c struct in multiple file error: dereferencing pointer to incomplete type
我试图声明一个结构,并在多个文件中使用它,但遇到了我无法弄清的错误。 示例代码发布在下面。
在test.h中
#ifndef TEST_H
#define TEST_H
struct mystruct;
struct mystruct *new_mystruct();
void myprint(struct mystruct*,int);
#endif
int test.c
#include "test.h"
#include <stdio.h>
#include <stdlib.h>
struct mystruct {
int *myarray;
};
struct mystruct *new_mystruct(int length)
{
int i;
struct mystruct *s;
s = malloc(sizeof(struct mystruct));
s->myarray = malloc(length*sizeof(int));
for(i = 0; i < length; ++i)
s->myarray = 2*i;
return s;
}
在main.c中
#include "test.h"
#include <stdio.h>
int main()
{
int len = 10;
struct mystruct *c = new_mystruct(len);
myprint(c, len);
printf("%f", c->myarray[3]); // error: dereferencing pointer to incomplete type
return 0;
myprint()打印出0 2 4 6 8 10 12 14 16 18.为什么myprint(函数不起作用,但printf语句不起作用?为什么可以将其传递给函数但不在main中使用它呢?谢谢。
当前main()
仅知道struct mystruct
是一个类型,但对其内部结构一无所知,因为您已将其隐藏在test.c中。
因此,您需要移动以下定义:
struct mystruct {
int *myarray;
};
从test.c到test.h,以便对main()
可见。
注意:您在这里所做的是不透明类型的经典示例。 当您想从将要调用您的API的代码中隐藏实现细节时,这可能是一种非常有用的技术。
Main.c不知道mystruct结构的内容。 尝试移动这些行:
struct mystruct {
int *myarray;
};
从test.c到test.h。
当您使用它时,我认为您的意思是“ int myarray”而不是“ int * myarray”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.