The Person_create function returns a pointer to a struct Person , so you need to define the return value as a pointer (by adding *). To understand the reason for returning a pointer to a structure, and not the structure itself, you need to understand how C processes memory.
When you call a function in C, you add an entry for it to the call stack . At the bottom of the call stack is the main function of the program in which you are working, at the top is the current function being executed. Entries in the stack contain information, such as parameter values passed to functions, and all local function variables.
There is another type of memory that your program has access to: heap memory. Here you allocate space using malloc and it is not connected to the call stack.
When you return from a function, the call stack is called and all information associated with the function call is lost. If you want to return the structure, you have two options: copy the data inside the structure before it pops out of the call stack, or save the data in heap memory and return the pointer to it. Copying a data byte for a byte is more expensive than just returning a pointer, and therefore you would usually like to do this to save resources (both in memory and in the processor cycle). However, this does not happen without cost; when you store your data in heap memory, you should remember free , when you stop using it, otherwise your program will leak memory.
Baldur Þór Emilsson
source share