PDA

View Full Version : returning string from a function?


nregi
06-10-2003, 01:40 PM
Hello,
Is there a way to return string locally created within a function?

Example:
char *retstr(int *intarr, unsigned int len) {
char str[len+1];
unsigned int l = 0;

for (l = 0; l < len; l++) {
str[l] = (char)intarr[l];
}
str[l] = '\0';

return str;
}


Thanks in advance.

sicarius
06-10-2003, 03:22 PM
In general you would want to pass a character pointer as an argument to the function. This may seem backwards, but it is how the language works. There are scope issues with local variables (i.e. when the scope runs out the local variables are reclaimed). So a pointer to a character array (a string) inside some fuction would only be valid for that function. Returning that pointed would most likely result in a segfault.
The way around this problem is to pass in a pointer from a higher scope (i.e. from the calling function, or a global variable). In this way you can insure that pointer will be valid for the scope it is going to be returned to.

So you may want to say:

char *retstr(int *inarr, unsigned int len, char *str) {

//you can either assume that the given pointer is
//of the correct size, or your can make it so.

str = (char *)malloc(len+1);

unsigned int l = 0;

//your subscript notation of course is still valid
for (l = 0; l < len; l++) {
str[l] = (char)intarr[l];
}
str[l] = '\0';

return str;

}


Also, I think that if you use the malloc() function it would be safe to return a character pointer without having a character pointer parameter for your function. This has something to do with where malloc gets the memory space from. I am not really sure of the details but you should see if the following also works:


char *retstr(int *inarr, unsigned int len) {

str = (char *)malloc(len+1);

unsigned int l = 0;

//your subscript notation of course is still valid
for (l = 0; l < len; l++) {
str[l] = (char)intarr[l];
}
str[l] = '\0';

return str;

}


If this second approach works, it may be better suited for what you need. Don't count on it to work for every platform though, some handle memory differently than others.

nregi
06-10-2003, 04:24 PM
Thank you for the reply,
How would the memeory allocated by malloc be freed?
Should the function calling retstr() free the memory?

Thanks again.

sicarius
06-10-2003, 04:50 PM
You would free the memory allocated by malloc by calling the
free() function at some appropriate time.

The appropriate time depends on how long you want that string variable to live. In other words the memory should be free before the scope of the variable runs out. So if you use the string returned by retstr in some function, and not as a global, then you would free the memory before the calling function returns.