#include<stdio.h>
typedef struct telephone
{
char *name;
int number;
} TELEPHONE;
int main()
{
//TELEPHONE index;
TELEPHONE *ptr_myindex;
ptr_myindex = (TELEPHONE*)malloc(sizeof(TELEPHONE));
//ptr_myindex = &index;
ptr_myindex->name = "Jane Doe";
ptr_myindex->number = 12345;
printf("Name: %s\n", ptr_myindex->name);
printf("Telephone number: %d\n", ptr_myindex->number);
free(ptr_myindex);
return 0;
}
When I compile this, it outputs the same result as when I don’t dynamically allocate the pointer to the struct, and instead use the part in my code that has been commented out. Why does this happen?
When you declare:
TELEPHONE indexThe compiler knows what kind of struct
TELEPHONEis and so it allocates the memory needed by that struct.For example:
It’s perfect. But if we want to achieve the same without
int a = 5, we should do the following:There’s a difference tough. The first code allocate the variable in the
stack, while the second code allocate it in theheap. But in the second case, there’s no allocated space for the struct before themalloc, and the only allocated space is for the pointer itself (that do not need the same space as the struct itself).