Friday, July 31, 2009

Can a function in C return a data type thta i made through struct?

OMg! Help! I need to do my homework.





If yes, ty. The error of my code must be somewhere else.


If no, OMg! I'm dead! Any other ways i could simulate this?

Can a function in C return a data type thta i made through struct?
Yes you can ... example :





struct wp_char{


char wp_cval;


short wp_font;


short wp_psize;


}ar[10];





struct wp_char infun(void)


{


struct wp_char wp_char;





wp_char.wp_cval = getchar();


wp_char.wp_font = 2;


wp_char.wp_psize = 10;





return(wp_char);


}





Hope this help
Reply:On a PC, the return value of a function is placed in the AX register - and your struct probably won't fit.





What you need to do is to return a *pointer* to the struct.





And that's bad practice.





The called function can't use an automatic variable for the struct, because when it returns that pointer, it will point to memory that's no longer allocated. If the called function mallocs space for the struct, then the calling function has to remember to free the memory when it's done with it. Too often, programmers use that same function later, forget that requirement, and end up with a memory leak.





Let the calling function create the struct as an automatic variable. Have the called function return a code indicating success or error as the return value. Believe me - I paid *dearly* to learn this lesson in writing code. Memory leaks are no fun at all.
Reply:yes





like this:





struct A


{


int a1;


char* s1;


};





struct A function(int a1, char* s1)


{


struct A retval;


retval.a1=a1;


retval.s1=s1;


return retval;


}
Reply:Yes to both questions.





You can return ANY data type from a function, but that doesn't mean you should!





When you return an object a copy of it is made and the copy is what is returned, this is slow and wasteful for large objects. And note that while your object will be copied any pointers it has may be invalid if they point to variables also declared inside the function which would have gone "out of scope".





A common and perferable alternative to returning a structure that would be bigger than say a few single int or long or doubles would be is to create a copy of your struct before calling your function and pass the function a pointer to it. eg


my_struct p;


my_func(%26amp;p);


See passing by reference vs passing by value


No comments:

Post a Comment