Paminu <sd**@asd.com > writes:
In the following code I am trying to initialize a pointer that is located in
a struct.
#include <stdlib.h>
#include <stdio.h>
#define KIDS 4
typedef struct test
{
void *content;
struct test_ *bob;
} test_;
[snip]
As you know by now, you need "struct test" for the declaration of bob,
not "struct test_". So let's look at the corrected code:
typedef struct test {
void *content;
struct test *bob;
} test_;
This declares a type called "struct test" (one of whose members is a
pointer to a "struct test"). It also create an alias for that type
called "test_".
In your original code, since you haven't declared something called
"struct test_", the compiler assumes it's an incomplete type. cyou
can declare a pointer to an incomplete type as long as you complete
the type later, which is why the compiler didn't complain. (At that
point, "struct test" is itself an incomplete type, completed at the
end of the struct definition.) This is what makes it possible for two
or more distinct structure types to contain pointers to each other.
Since struct tags are in a separate namespace, you can use the same
identifier for the struct and the typedef:
typedef struct test {
void *content;
struct test *bob;
} test;
Now you have two names for the same type: "struct test" and "test".
Here's the question: why do you need two names? Opinions differ on
this point, but in my opinion the typedef is not particularly useful.
I would just declare the type like this:
struct test {
void *content;
struct test *bob;
};
and simply refer to the type as "struct test" everywhere. The typedef
saves you a little typing, but that's not a good enough reason to use
it; the keystroke shortage ended some time ago.
It makes sense to use a typedef for a structure if you want to hide
the fact that it's a structure; for example, code that uses the type
FILE in <stdio.h> doesn't need to know that it's a structure. That's
not the case here.
--
Keith Thompson (The_Other_Keit h)
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.