繁体   English   中英

C中的结构,编译器错误

[英]Structs in C, compiler error

我收到此错误:

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

编译以下代码时。 怎么了

#include <stdio.h>

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);

}

看起来您想让addpoints返回一个struct point ,但是您忘了在struct之后插入point

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

但是,除非您将struct point的定义从main拉出,否则这仍然行不通:

#include <stdio.h>

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){

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

在使用它之前还要声明您的struct point类型,在这里您要在main函数中声明struct point

很多问题:

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这样的全局函数无法访问它。 您必须将它带到外面,并且必须在函数加点之前。 因为C解析器使用自上而下的方式来解析代码。 如果您有在使用之前从未出现过的东西,它将告诉您, first declaration of something

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM