Reputation: 11
I am studying structures in C from K&R book and encountered this:
struct{
int len;
char *str
} *p;
I am confused by this, because where the name of the struct variable should be, they have given a pointer *p
. Can anyone please help me here? What does this declaration mean?
Upvotes: 1
Views: 72
Reputation: 12424
This declaration is a pointer to a struct which is composed of 2 fields — an int
and a char*
. This struct doesn't have a name and if you want to declare another pointer of the same struct, you will have to write it again.
Notice you can write something like this:
struct MyStruct {
int data1;
char data2;
};
This will define a new struct type which you can use later like this to declare a variable: struct MyStruct myVar;
. The difference from what you wrote is that this struct doesn't declare a new variable but a new type since the struct in my example has a name and yours does not.
Another option is to use a typedef
and give this struct a name and then you can use the name you have given it to declare more variables of that type.
You can read more about it at http://en.wikipedia.org/wiki/Typedef in the "Simplifying a declaration" section.
Upvotes: 3