【发布时间】:2014-04-11 17:35:46
【问题描述】:
我已经搜索并找到了许多从函数返回字符数组的解决方案,但它们都不起作用。我确信这在 C 中一定是可行的。 基本上,这就是我想做的。
char* Add( )
{
char *returnValue = (char *) malloc( sizeof(char) * 3 );
returnValue = "test"; //This doesn't work. I'm not at all interrested in doing returnValue[0] = 't', returnValue[1] = 'e', etc.
return returnValue;
}
我希望你明白我想在这里做什么。
【问题讨论】:
-
查看
strcpy()。也不要期望能够将长度为 4 的字符串(+ 一个尾随 NULL)存储在 3 个字符的数组中。或者只是return "test";(然后你必须返回一个const char *。) -
return strcpy(malloc(sizeof(char) * 5), "test");