我收到的错误是取消引用指向不完整类型的指针
,但我已在另一个文件中使用该结构两次并且工作得很好。为什么当我在 main 中第三次尝试使用它时会出现此错误?显然我使用了不同的名称,这意味着结构不完全相同。
这里我定义了结构
//bom.h
#ifndef BOM_H_INCLUDED
#define BOM_H_INCLUDED
struct polyinfo {
int size;
int poly[];
};
struct polyinfo *createpoly(struct polyinfo *s, int sz, int p2[]){
int i;
s=(int*)malloc(sizeof(*s) + sizeof(int)*sz);
s->size=sz;
for(i=0;++i<sz;)
s->poly[i]=2*p2[i];
return s;
};
int* bom(int s[], int n);
#endif // BOM_H_INCLUDED
这里我使用了两次,效果很好
//bom.c
#include <stdio.h>
#include "bom.h"
int* bom(int s[], int n){
int i;
int *s2;
struct polyinfo *s3;//using the structure of polyinfo
struct polyinfo *s4;//using the structure of polyinfo 2nd time
s4 = createpoly(s4, n, s);//creating a poly multiply by 2
printf("printing 2nd:");
for(i=0;++i<n;)
printf("%d", s4->poly[i]);
printf("\n");
s2=(int*)malloc(n*sizeof(int));
printf("received n= %d\n",n);
for(i=0;++i<n;)
printf("%d", s[i]);
printf("\n");
for(i=0;++i<n;)
s2[i]=2*s[i];
s3 = createpoly(s3, n, s);//creating a poly multiply by 2
printf("printing the struct, poly size: %d\n",s3->size);
for(i=0;++i<n;)
printf("%d ", s3->poly[i]);
printf("\n");
return s2;
}
尝试第三次使用它时出现错误:取消引用指向不完整类型的指针
//main.c
#include <stdio.h>
int main(){
int i, s[]={1,1,1,0,1};//the pattern that will go
int n=sizeof(s)/sizeof(*s);//size of the pattern
int *p;//sending the patt, patt-size & receiving the poly
struct polyinfo *s5;//using the structure of polyinfo 3rd time
s5 = createpoly(s5, n, s);//creating a poly multiply by 2
printf("printing 2nd:");
for(i=0;++i<n;)
printf("%d", s5->poly[i]);
printf("\n");
p=bom(s, n);
for(i=0;++i<n;)
printf("%d", p[i]);
return 0;
}
如果我尝试在 main.c 中使用 #include "bom.h",错误是多重定义
最佳答案
您的代码中实际上有两个问题,您需要修复这两个问题。只解决一个问题而不解决另一个问题(这基本上是您所尝试过的)是行不通的。
1) 目前 createpoly()
在 header 中定义(也称为实现),因此每个编译单元 #include
该 header 将获得自己的定义 - 这会导致程序在大多数情况下无法链接。最简单的解决方法是仅在 header 中声明该函数,并在一个源文件中定义它(最好也包含该 header )。还有其他选择 - 例如,在函数定义前加上 static
前缀。 - 但此类选项会产生其他后果(例如,导致每个目标文件都有自己的函数本地定义),因此最好避免使用,除非您有特定需要这样做。
2) 前向声明足以声明指针(例如代码中的 struct polyinfo *s5
),但不足以取消引用该指针(例如 printf("%d", s5->poly[i])
)。对于您的情况,解决方案是将 header (具有 struct polyinfo
的定义)包含在 main.c
中。 。
关于c - 如何在不同文件中使用struct C编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080641/