I believe, when you call sizeof
on a struct
type, C recursively calls sizeof on the fields of the struct
. So, struct st *x = malloc(sizeof(struct st));
only really works if struct st
has a fixed size. This is only significant if you have something like a variable sized string in your struct and you DON'T want to give it the max length each time.
In general,
struct st *x = malloc(sizeof(struct st));
works. Occasionally, you will run into either variable sized structs or 'abstract' structs (think: abstract class from Java) and the compiler will tell you that it cannot determine the size of struct st. In these cases, Either you will have to calculate the size by hand and call malloc with a number, or you will find a function which returns a fully implemented and malloc'd version of the struct that you want.