Originally Posted by
|HBO|
Long time no see. I am stuck with sth. How can i return a variable (char) from this function?
You need to return a pointer to a string. The string cannot be local to the function, since it will cease to exist when the function returns. So you use malloc() to put it on the global heap:
Code:
#include <stdio.h>
#include <string.h>
char *eg() {
char *p = malloc(12);
strcpy(p, "hello world");
return p;
}
int main() {
char *test = eg();
puts(test);
free(test);
return 0;
}
It's important to free() malloc'd memory when you are done with it.
Alternately, you can submit a pointer and fill it in:
Code:
#include <string.h>
#include <stdio.h>
void eg(char *p) {
strcpy(p, "hello world");
}
int main() {
char test[12];
eg(test);
puts(test);
return 0;
}