Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 928
user2021512 Avatar asked Dec 09 '22 18:12

user2021512


1 Answers

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".

like image 145
unwind Avatar answered Dec 11 '22 12:12

unwind