C structures do not define types?

I just started learning C with a professional Java background and some (if not too much) C ++ knowledge, and I was amazed that this did not work in C:

struct Point {
    int x;
    int y;
};

Point p;

p.x = 0;
p.y = 0;

It seems that I should declare pusing struct Pointas type or using typedef. Does this code work on C99? Or is it a "C ++ thing"?

+3
source share
10 answers

As far as I know, it should not work without typedefin C99 either (since this is just the way C works), but it works in C ++, since structin C ++ it is just classwith all the public members by default.

+7
source

No, the structure does not define a new type. What you need:

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

Now Point - , :

Point p;
p.x = 0; p.y = 0;
+5

struct Point - , union Foo . typedef - typedef struct Point Point;.

+4

C

struct Point {
    int x;
    int y;
};

union Point {
    int x;
    int y;
};

, struct Point union Point .

6.7.2.1 C99 :

6 . struct union , , , .

7 struct-declaration-list struct-or-union-specifier .

. C 6.7.6 -- 6.7.2, struct-or-union identifier.

C99? "++ "?

, C99 . "++ ", ++, ++.

+4

...

Point           a tag
struct Point    a type

typedef struct {
    . . .
} Point_t;

Point_t         a type

?, . , Point x;, ?

, C . 4 1. , struct , .


1. 4 :
- ( );
- , ( ) struct, union enum);
- ; ( , . → );
- , ( )

+2

C99 , ++. struct Point, typedef C.

+1

. :

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

, typedef. C, ++:

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

, , .

+1

C : . , , :

struct mytag { int a; }
struct mytag mystruct;

typedef . :

typedef struct mytag { int a; } mytype;
mytype mystruct; // No struct required
+1

, . C :

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

And then you will have a type called Pointthat will do what you want.

In C ++, it's enough to define it the way you did it.

0
source

First you need to make Point the following type:

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

This allows use Pointas a type, orstruct Point

i.e:

Point *p;

sizeof(struct Point);

Some people prefer the structure name to be different from the type being created, for example:

typedef struct _point {
       ...
} Point;

You will encounter both. The last example tells me that I should not use struct _point, it cannot be used, except as a type Point.

0
source

Source: https://habr.com/ru/post/1722915/


All Articles