C structs don't define types?

前端 未结 10 2205
离开以前
离开以前 2021-01-21 06:54

I\'ve just started learning C with a professional Java background and some (if no too much) C++ knowledge, and I was astonished that this doesn\'t work in C:

str         


        
10条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 07:21

    Structs are not types. You can create a point from a struct as follows:

    struct Point p;
    p.x = 0;
    p.y = 0;
    

    If you want to use a struct as a type, you have to typedef it. This works in both C and C++:

    typedef struct _point {
        int x;
        int y;
    } Point;
    

    Always give your struct a name though, if you have to forward declare it to be able to have pointers to a struct of the same type or circular dependencies.

提交回复
热议问题