In K&R Chapter 6, a declaration is mentioned as follows:
struct{
int len;
char *str;
} *p;
I couldn't understand which structure is this pointer p pointing to and if such a pointer definition is even valid because in all other examples given in the book and the ones I have seen otherwise, when defining a pointer to a structure, the name of the structure, that is, the type being defined needs to be mentioned. For example,
struct example{
int a;
...
}s1;
and then,
struct example *ptr = &s1;
so, it is mentioned that ptr is pointing to a type struct example and not just struct.
Also, of particular interest was this:
*p->str fetches whatever str points to; *p->str++ increments str after accessing whatever it points to (just like *s++);
I couldn't follow what p is in the first place, hence, not the increment and dereference as well.
What is going on here?
Thanks in advance!
P.S. I am new here, so any feedback on the format of the question would also be appreciated.
The struct
keyword works sort of like an extended version of typedef
, except that you create a complex custom type (called a structure) instead of aliasing an existing type. If you only have one thing that needs to use the declared type, you do not need to provide an explicit name for the type.
The first statement you are looking at declares a structure with two fields, but does not name it. This is called an anonymous structure. The declaration does, however, provide a pointer of that type.
One possible use-case for such a declaration is when you make a header for an external library, possibly one that is not even written in C. In that case, the type of the structure may be opaque or incomplete, and you just need to have a convenient reference to some parts of it. Making the structure anonymous prevents you from being able to allocate it yourself easily, but allows you to interact with it through the pointer.
More commonly, you will see this notation used in conjunction with named or at least aliased structures. The second statement could be rewritten as
struct example { ... } s1, *ptr;
In that case, struct example *ptr = &s1;
would be just ptr = &s1;
.
An even more common occurrence is the use of anonymous structures with typedef
, create custom type names that do not include the struct
keyword. Your second example could be rewritten as
typedef struct { ... } example, *pexample;
example s1;
pexample ptr; // alternatively example *ptr;
ptr = &s1;
Note that the type of s1
is example
and not struct example
in this case.