#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Name *NameFunc(struct Name *);
struct Name
{
char *Fname;
char *Lname;
};
int main()
{
struct Name *name1, *name2;
name1 = (struct Name *)malloc(sizeof(struct Name));
//name2 = (struct Name *)malloc(sizeof(*name2));
name1->Fname = (char *)malloc(50 * sizeof(char));
name1->Lname = (char *)malloc(100 * sizeof(char));
strcpy(name1->Fname, "Akhil");
strcpy(name1->Lname, "Sambaraju");
printf("%s %s\n", name1->Fname, name1->Lname);
name2 = NameFunc(name2);
printf("%s %s", name2->Fname, name2->Lname);
return 0;
}
struct Name *NameFunc(struct Name *name)
{
name->Fname = "Akhil";
name->Lname = "Sambaraju 2.0";
return name;
}
OUTPUT: Akhil Sambaraju Akhil Sambaraju 2.0
How is this code running properly even though i havent allocated memory to 'name2'? After some messing around with commenting, i found that the function call NameFunc() has nothing to do with it. But 'name1' has. If i dont allocate memory to name1 using malloc, it doesnt print out anything on cmd. When I intialise name2 to NULL, it just prints out "Akhil Sambaraju" i:e name1. Why does allocating memory to name1, allocate memory to name2 as well(when not initialised)? PS: why does intialising fname and lname to NULL in struct Name give an error?