The function is used malloc(xx) where xx is an int

calculates the size of the structure in bytes

In C, malloc returns a void* pointer (It is a generic type that can be assigned to any type of pointer)

malloc reserves that space in memory and returns a pointer to it

a cast (yyyy) must be done so that the compiler knows that the returned pointer is of type yyyy

This allows a new instance of yyyy to be created in dynamic memory

if yyyy is a struct:

yyyy* str = (yyyy*) malloc(sizeof(yyyy)); 

(yyyy) is an explicit cast that converts the void pointer returned by malloc to a pointer of type yyyy*

The cast (yyyy*) is optional in C, since the compiler can do the conversion implicitly

typedef struct {
    int a;
    char b[40];
} YYYY;

YYYY* str = malloc(sizeof(YYYY));
str->a = 1;

Some programmers prefer to include the explicit cast for several reasons:

  • Makes the code clearer and more explicit about the type of pointer being used
  • In some cases, this may be necessary to avoid compiler warnings or to ensure compatibility with different versions of C