[英]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.