Steve Edwards <gf*@lineone.net> writes:
How do I create a new type of structure that contains a pointer to its
own type? i.e.
typedef struct{
string tag;
TagPtr *subPtr;
} TagPtr;
(...which won't compile as it doesn't know what TagPtr is for subPtr.)
I presume you have a type called "string" somewhere. You really
shouldn't, since names starting with "str" are reserved, but we'll
leave that aside for the moment.
struct TagPtr {
string tag;
struct TagPtr *subPtr;
};
There's really no need for a typedef; just refer to the type by its
name, "struct TagPtr". <OT>C++ would let you call it "TagPtr"; C
doesn't.</OT>
If you insist on having a second name for the type, you can use a
typedef:
typedef struct TagPtr {
string tag;
struct TagPtr *subPtr;
} TagPtr;
This creates a structure type called "struct TagPtr", and an alias for
that type, "TagPtr". Struct tags and typedefs are in distinct
namespaces, so it's ok to use the same identifier for both. Now you
can refer to the type either as "struct TagPtr" or as "TagPtr". The
name "TagPtr" becomes visible only after the end of the declaration,
so within the declaration you can refer to it only as "struct TagPtr".
A lot of programmers do it this way, but if you drop the typedef, you
only have one name for the type, and you don't have to remember which
one you can use where.
Your terminology is confusing. The identifier following the keyword
"struct" is called a struct tag; additionally using the word "tag"
both as part of the type name and as a member name makes it hard to
keep track of everything. An identifier ending in "ptr" or "Ptr"
usually implies a pointer, but "struct TagPtr" is not a pointer type
(but subPtr is a pointer).
Finally, what is a "string"?
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.