-2
    #include<stdio.h>

    typedef struct
    {
        int *u;
        struct node next;
    } *node;

    int main()
    {
        return 0;
    }

What is meant by *node here? I don't get it. I think there should be a node here but it is compiling anyway.

adripanico
  • 1,026
  • 14
  • 32
Suraj Menon
  • 1,486
  • 3
  • 28
  • 50

5 Answers5

2

Here typedef defines a new type, node, which is a pointer to the structure.

The code in the question may not compile since struct node doesn't appear to be defined anywhere and yet it's used inside of the structure.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
0

Compare this:

typedef int * pointer_to_int;

Here, the asterisk is part of the type being given a new name, i.e. pointer_to_int is an alias for the type int *.

With your example, it's exactly the same! The asterisk is part of the type, so that node becomes an alias for the type pointer to struct node { int *u; struct node *next; }.

Also, note that it's often a bad idea to include the asterisk in typedef, since it makes the code much harder to use. In C, it's often very interesting to know whether a variable is a pointer or not, so hiding that fact isn't very helpful.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

The correct definition is:

typedef struct Node {
    int *u;
    struct Node *next;
} *node;

In your code there is a problem in a struct declaration; syntax is:

struct identifier/tag {struct declaration list}

struct declaration list is a sequence of declarations for the members of the structure;

typedef declaration provides a way to create an alias, a synonym for the type; syntax is:

typedef type alias

Where is the Error?

typedef struct { 

In this case there isn't an alias!

b3h3m0th
  • 1,330
  • 1
  • 11
  • 22
0

problems here:

typedef struct
    {
        int *u;
        struct node next; //struct node is NOT defined.
    } *node;

This is wrong:

it should be :

typedef struct node{
   int *u;
   struct node *next;
}*nodeptr;

This code means that "nodeptr" is a pointer to struct node;

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

Personally, I've never seen this kind of declaration. This use to be something like:

typedef struct {
  int *u;
  struct node *next;
} node;

And that's simple: you are defining a structure with a pointer to an integer and a pointer to another element of the same structure.

adripanico
  • 1,026
  • 14
  • 32
  • 1
    In your code, the `struct` is anonymous. Thus field `next` is not a pointer to a similar `struct` but to an undefined `struct node`. The `typedef` has nothing to do with the name of the `struct` itself (`typedef struct { ... } name` is more or less equivalent to `struct __anonymous__ { ... }; typedef struct __anonymous__ name`) – Virgile Oct 19 '12 at 13:00