Saturday, May 22, 2010

Passing strings in C?

I'm pretty new to C and need help with strings. I also have no idea about the differences between C and C++, so please only help with info on C and not C++ or C#.





If I created a string in a function and want to pass it as a return value for the function to use in other functions, how can I do this without loosing the string when the function ends?





I know that when a function ends, everything that is local to it gets, for a better word, destroyed. If you can only return/pass the pointer to the string created in the function, when the function ends, won't the actual string be destroyed/reallocated and the pointer be essentially useless? How can I return the actual string/keep it for use in other functions?

Passing strings in C?
ok.... you have the basics right. so this is what you need to do





char * foo() {


int str_size = 6; //example size.


char * x = (char *) malloc(sizeof(char)*str_size);


sprintf(x, "%s", "hello");


return x;


}





the malloc is allocation memory from the heap. this will ensure that even when you exit the foo method, the location is not reclaimed. And you return the address to the same.


So you should be fine.
Reply:but don't forget to free() the pointer when you don't need it anymore, otherwise you will have a memory leak.


No comments:

Post a Comment