问题
How to return a local character array from one function
char* testfunction()
{
char array[] = "Hello World";
return array;
}
char main()
{
char* array = testfunction();
printf(" %s -> string", array);
return 0;
}
THis code results unknown error
�@$�@<��Ʉ�;���Y@��� -> string
回答1:
You should not return the address of the stack variable directly as it is destroyed once the stack frame is removed(after the function returns).
You could do this.
#include <stdio.h>
#include <algorithm>
char* testfunction()
{
char *array = new char[32];
std::fill(array, array + 32, 0);
snprintf(array, 32, "Hello World");
return array;
}
int main()
{
char* array = testfunction();
printf(" %s -> string", array);
delete[] array;
return 0;
}
回答2:
You are returning a pointer which points to a local variable, when testfunction()
returns array
in main() becomes dangling pointer.
use std::string instead
#include <string>
#include <iostream>
std::string testfunction()
{
std::string str("Hello World");
return str;
}
int main()
{
std::cout << testfunction() << std::endl;
return 0;
}
回答3:
Perhaps, this is what you want:
const char *testfunction(void)
{
return "Hello World";
}
回答4:
You can't return the address of a local variable. (if you use gcc you should get some warnings)
You can try to use the keyword static
instead:
char *test()
{
static char array[] = "hello world";
return (array);
}
来源:https://stackoverflow.com/questions/18444271/return-local-character-array-from-a-function