C中的结构,编译器错误

我收到此错误:

str.c:5:19: error: expected identifier or '(' before 'struct' 

编译以下代码时。 这有什么问题?

 #include  struct addpoints (struct point p1, struct point p2){ p1.x += p2.x; p1.y += p2.y; return p1; } int main(){ struct point{ int x; int y; }; struct point p1 = { 13, 22 }; struct point p2 = { 10, 10 }; addpoints (p1,p2); printf("%d\n", p1.x); } 

 struct addpoints (struct point p1, struct point p2){ 

struct不是一个类型。 struct point是一种类型。

在使用之前声明你的struct point类型,这里你在main函数中声明了struct point

看起来你想要addpoints来返回一个struct point ,但是你忘了在struct之后放入point

 struct point addpoints (struct point p1, // ... 

但是,除非您将struct point的定义从main拉出来,否则这仍然无效:

 #include  struct point{ int x; int y; }; struct point addpoints (struct point p1, struct point p2){ p1.x += p2.x; // ... 

很多问题:

 struct addpoints (struct point p1, struct point p2){ p1.x += p2.x; p1.y += p2.y; return p1; } 

乍一看,我很惊讶,我不记得C有这种语法吗? 我一定是个傻瓜。 然后我看,它是一个函数,返回类型是struct,这显然是错误的。

struct是一个声明结构而不是类型的关键字。 如果要返回结构类型,则需要结构名称。 在您的情况下,您应该使用:

 struct point addpoints(struct point p1, struct point p2){//...} 

您的struct point也在主函数内,而不是全局。 因此像addpoints这样的全局函数无法访问它。 你必须把它带到外面,并且必须在function添加点之前。 因为C解析器使用up-to-down来解析代码。 如果你有一些在使用之前从未出现过的东西,它会告诉你, first declaration of something