The Seeker
The Seeker

Reputation: 632

please explain the behaviour of typedef here

int main()
{
  int a;
  typedef struct  
  {
      int i;
      int j;
  }type1;
  typedef type1 type[10]; //Please explain this line ?
  typedef struct 
  {
      int  l;
      type  c;
  }type2;

  type2 x;
  x.c[0].i=1;   //How can we write this??
  x.c[0].j=2;

  x.c[2].j=3;

  printf("%d",x.c[2].j);
  return 0;
}

Program is compiling successfully which I'm expectecting not to because of

    typedef type1 type[10];

Please explain the behavior of typeded here.All I know is that we can define an alias with the help of typedef.

output:3

Upvotes: 4

Views: 198

Answers (1)

unwind
unwind

Reputation: 400159

The way to read typedef is as a regular variable declaration, with the variable's type being the type that is being given an alias, and the variable name being the name of the new alias.

So, in

typedef type1 type[10];

if we drop the typedef we get:

type1 type[10];

This clearly defines type to be an array of 10 type1. So, the typedef is then introducing the name type for the type "array of 10 type1".

Upvotes: 14

Related Questions