2
typedef struct{
    char name[25];
    int yearOfBirth;
    int district;
    char gender;
    int age;

    CitizenType *next;

}CitizenType;

When I try to make a Linked List in this format in Visual Studio, I get all sorts of errors relating to syntax. (102 in total) but when I comment out the CitizenType *next; I get no errors. I realize it has something to do with referencing the structure before it has been completely declared, but I have no idea how to fix this.

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
Dave McGregor
  • 89
  • 1
  • 6

3 Answers3

4

Declare the typedef before (and separately from) the structure.

typedef struct citizen_type CitizenType;

struct citizen_type {
    ...
    CitizenType *next;
};
1

The problem is that

CitizenType

enters into the namespace of types only after the structure ends.

So you can use the new type only after its declaration.

You can use instead of it a struct name (giving a name to the struct), or declaring the type before to declare the structure with a name, as in previous post.

alinsoar
  • 15,386
  • 4
  • 57
  • 74
0

Try this:

typedef struct node{
    char name[25];
    int yearOfBirth;
    int district;
    char gender;
    int age;

    struct node *next;

}CitizenType;

Check this stack overflow answer for more information about self referenced structs in C. From the answer:

A CitizenType cannot contain another CitizenType as it becomes a never-ending recursion.

Hope it helps!

Community
  • 1
  • 1
Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
  • 1
    It compiles! Thank you! I'll have to do some reading. Much appreciated. – Dave McGregor Nov 04 '12 at 03:06
  • great @DaveMcGregor, mark this answer or the one that you like the most as 'the answer' of your question. For more info about the site I recommend you to read the [faq](http://stackoverflow.com/faq). Welcome to SO! – Cacho Santa Nov 04 '12 at 03:08
  • 2
    @cacho umm.. He is pointing to another CitizenType and not creating a never-ending recursion.. I think the reason his original code did not work is that typedef should appear before it is actually used. By replacing it with struct node *next, you are just not using the typedef before it is defined. I think your answer is a bit misleading. – Neo Nov 04 '12 at 03:10
  • @Neo, I understood that the recursion(from the answer linked) it refers that you are trying to define a datatype, but inside the datatype is the datatype itself. Sorry if I am not very clear with this, do we agree now? – Cacho Santa Nov 04 '12 at 03:14