C structs don't define types?

前端 未结 10 2201
离开以前
离开以前 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:08

    You first need to make Point a type like :

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

    This allows you to use Point as a type, or struct Point

    I.e:

    Point *p;
    
    sizeof(struct Point);
    

    Some people prefer to make the name of the structure different from the type being created, such as:

    typedef struct _point {
           ...
    } Point;
    

    You'll run into both. The last example tells me that I should not use struct _point, its not meant to be exposed except as the type Point.

    0 讨论(0)
  • 2021-01-21 07:18

    No, a struct do not define a new type. What you need is:

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

    Now Point is new type you can use:

    Point p;
    p.x = 0; p.y = 0;
    
    0 讨论(0)
  • 2021-01-21 07:20

    struct Point is the type just like union Foo would be a type. You can use typedef to alias it to another name - typedef struct Point Point;.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题