You’re on the right track
Both the reasons you mentioned are valid:
“One of the reasons I thought that is would be an advantage to return a pointer to a structure is to be able to tell more easily if the function failed by returning NULL pointer.“
One of the reasons I thought that is would be an advantage to return a pointer to a structure is to be able to tell more easily if the function failed by returning NULL pointer.
“Returning a FULL structure that is NULL would be harder I suppose or less efficient. Is this a valid reason? “
Returning a FULL structure that is NULL would be harder I suppose or less efficient. Is this a valid reason?
If you have a texture (for example) somewhere in memory, and you want to reference that texture in several places in your program; it wouldn't be wise to make a copy every time you wanted to reference it. Instead, if you simply pass around a pointer to reference the texture, your program will run much faster.
The biggest reason though is dynamic memory allocation. Often times, when a program is compiled, you aren’t sure exactly how much memory you need for certain data structures. When this happens, the amount of memory you need to use will be determined at runtime. You can request memory using ‘malloc’ and then free it when you are finished using ‘free’.
A good example of this is reading from a file that is specified by the user. In this case, you have no idea how large the file may be when you compile the program. You can only figure out how much memory you need when the program is actually running.
Both malloc and free return pointers to locations in memory. So functions that make use of dynamic memory allocation will return pointers to where they have created their structures in memory.
Also, in the comments I see that there’s a question as to whether you can return a struct from a function. You can indeed do this. The following should work:
struct s1 {
int integer;
};
struct s1 f(struct s1 input){
struct s1 returnValue = xinput
return returnValue;
}
int main(void){
struct s1 a = { 42 };
struct s1 b= f(a);
return 0;
}