Return Structure from Function (C)

arrays, c, function, malloc, structure

Solution

// make the structure def global so that main() and fun() know about it.
struct retValue {
 int number;
};    

// function fn returns a pointer to the structure retValue
struct retValue * fn() {     

 struct retValue* st = malloc(sizeof(*st));

 // return the pointer to the newly allocated structure.
 return(st);   
}

int main() {

 // call fn() to create a new structure dynamically.
 struct retValue *st = fn();
}

Problem

I need to create a structure inside a function (dynamically with malloc) Then i need to be able to send it to my main, and use it there. I have no problems creating it, I simply need help sending it to my main, and I'm also unsure of how to access it once I get it there. ``` struct retValue * fn() { struct retValue { int number; }; struct retValue* st = malloc(sizeof(*st)); return(???); } ``` That is the code i have so far. Thanks for any help. Let me know if you need something clarified. EDIT: Ok Some clarification is needed. What I am trying to achieve, is the ability to pass a structure through a function to my main. Inside the function i must declare variables, and assign them values. Then in the main I must print each variable of the structure to the screen. No global variables can be used (and thus i assume no global structures). Hopefully that clarifies things. EDIT 2: I've figured out my problem. For those interested, I needed to have the structure prototype outside of my functions first. Then i could pass st and then access it properly. Thanks to all, and sorry for the poor wording.

Original source