Structs in C, compiler error

2019-09-16 10:29发布

问题:

I get this error:

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

when compiling the following code. What is wrong with it?

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

}

回答1:

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

struct is not a type. struct point is a type.

Also declare your struct point type before using it, here you are declaring struct point in main function.



回答2:

It looks like you want addpoints to return a struct point, but you forgot to put in point after struct:

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

However, this will still not work unless you pull your definition of struct point out of main:

#include <stdio.h>

struct point{
    int x;
    int y;
};

struct point addpoints (struct point p1, struct point p2){
    p1.x += p2.x;
    // ...


回答3:

Many problems:

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

At the first glance, I was surprised, I don't remember C has this syntax? I must be stupid again. Then I see, it is a function, and return type is struct, which is apparently wrong.

struct is a keyword to declare a struct, not a type. If you want to return a struct type, you need the struct name. In your case, you should use:

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

Also your struct point is inside your main function, not global. So a global function like addpoints cannot access it. You must take it outside, and has to be before function addpoints. Because C parser uses up-to-down to parse the code. If you have something that never appear before the usage, it will tell you, first declaration of something



标签: c struct