Is it possible to return string from a function without calling malloc
?
I have a function as below:
char* getString(){
char tempStr[20]
// open file, read char by char and assign to tempStr
// ....
char* str = (char*)malloc(sizeof(char)*20);
strcpy(str, tempStr); // assume this copy the null terminating char as well
return str;
}
And then when I call the getString()
, I assign the return value to a char*
, and then free it when I'm done, just like below:
void randomFunction(){
char* line = NULL;
int i = 0;
while (i < 1000) {
line = getString();
// do stuff with line
free (line);
line = NULL;
}
}
However, I am wondering if there is any way to do this without malloc
? And, is this the proper way of returning string from a C function?
I tried to do some research regarding how to return without malloc
, but didn't find clear answers. I am new to C and still learning.