Pointer to struct vs struct tag?

Hello guys,

#include<stdio.h>
#include<stdlib.h>
  
  struct  newtype {
      char name;
  };
   
  int main() {
       struct newtype a ;
       struct newtype  *b = malloc(10 * sizeof(struct newtype));
       b -> name = 'Z';
       a.name = 'P';
       printf("Character to print1: %c\n",b->name);
       printf("Character to print2: %c\n",a.name);
  }

In my above code, I cant distinguish between the struct tag and pointer to struct. Are they both same ?? What exactly is the difference between b ā†’ name = ā€˜Zā€™; and a.name = ā€˜Pā€™; ?

Yes, they are the same in terms of a variable but different in terms of memory allocation. The memory for variable a is allocated statically in stack memory during compile time and memory for variable b is allocated dynamically in the heap memory during runtime. The main difference is that the statically allocated memory get deleted when the function exits and the dynamically created memory must be freed, manually.

4 Likes

@Mr.Tesla cheers mate! You are awesome man!!