What is the difference between struct composition and typedef?

78 Views Asked by At

Whether use struct to compose a struct type or use typedef to define an alias to the struct, the result looks the same. What is the difference between these two forms?

#include <stdio.h>

struct TypeDefinition{
  int a;
};

typedef struct type_id {
  struct TypeDefinition type_;
} type_id_t;

typedef struct TypeDefinition Type2;

int main()
{
  struct TypeDefinition type_def = {
    .a = 10
  };

  type_id_t * p_type = (type_id_t *)&type_def;
  Type2 * p_type2 =  &type_def;

  printf("value:%d\n", p_type->type_.a);
  printf("value(type_2):%d\n", p_type2->a);
  printf("size1:%ld, size2:%ld\n", sizeof(struct TypeDefinition), sizeof(type_id_t));

  return 0;
}

By using gdb to debug the program, the addresses of p_type and p_type2 are same. The content of that address is also be same.

0

There are 0 best solutions below