Well, it is how the language work. It automatically reserves memory for the type you ask for. If you ask for a struct student
, it reserves memory for a struct student
. If you ask for a pointer
, it reserves memory for a pointer
.
Example with int
:
int n; // Reserves memory for an int
int *p; // Reserves memory for a pointer (that points to an int)
// but there is no memory allocated to hold the int
// p needs to be initialized before you dereference it (i.e. *p)
p = malloc(sizeof(int)); // Initialize p and allocate memory to hold the int
if (!p) exit(1); // Error - no memory available
*p = 5; // Now p can be used
free(p); // Release the memory
Your case is not different than the example above. S2 is a struct student
while S1 is a pointer (to a struct student
) and you need to initialize S1 by allocating memory for a struct student
. Like:
S1 = malloc(sizeof(struct student));