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