-2

If I created a structure:

struct student {
int id;
char name [20];
student * next};

What is the meaning of:

typedef struct student student?

What does student * next?

Thank you!

engc
  • 25
  • 2
  • 8
    Have you considered reading an [introductory book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list)? – Georg Fritzsche Feb 07 '12 at 14:21

4 Answers4

3

A typedef creates a new name. Thus these are completely equivalent:

student *next;
struct student *next;

In your example the struct and the typedef have the same name. But it could be like this:

struct something {
/* ... */
};

typedef struct something student;

The declaration of a typedef looks like the type it introduces.


As a side side note, things are different in C++.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • And you can short cut doing `typedef struct something { ... } something;` – Eregrith Feb 07 '12 at 14:24
  • @Eregrith: Or even `typedef struct { ... } something;` – Niklas B. Feb 07 '12 at 14:25
  • 2
    The shortcut does not work, however, when you want the struct to contain pointers to itself. In this case, if you want to use the typedef name inside the struct definition, you need to first typedef the incomplete struct type before defining the struct. – R.. GitHub STOP HELPING ICE Feb 07 '12 at 14:38
1

typedef struct student student;

This create an alias for struct student with the name student.

Structure tags and type names live in two different namespaces in C (not true in C++), so it is allowed to use the same name for the alias and for the tag.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

In C, whenever using structs you have to use the keyword struct. By typedefing typedef struct student student, you're able to say struct student by simply saying student.

Phonon
  • 12,549
  • 13
  • 64
  • 114
0

With a named structure, the keyword struct most usually be used to create instances of the structure and to reference the structure type at all.

The typedef allows you to virtually create an alias for student instead of having to use struct student constantly, thereby actually making it behave more like a built-in type.

Kaganar
  • 6,540
  • 2
  • 26
  • 59