我搜索并找到了数十种从函数返回字符数组的解决方案,但没有一个有效。我确信这在 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;
}
我希望你明白我想在这里做什么。
最佳答案
作业 returnValue = "test"
使 returnValue
变量指向内存中的不同空间。它不会影响您刚刚分配的空间 malloc
;此外,由于这个空间不再被引用,它将保持分配状态但不会被使用,直到您的程序退出。
您需要将字符串复制到刚刚分配的空间中。标准库中有一个函数:strcpy
(在 <string.h>
中声明)。注意 strcpy
不检查目标缓冲区是否足够大,您需要在调用它之前确保这一点。
您要返回的字符串有 4 个字节长,加上空终止符为 5 个字节。因此您需要分配(至少)5 个字节,而不是 3 个字节。
char* Add()
{
char *returnValue = malloc(sizeof(char) * 5);
strcpy(returnValue, "test");
return returnValue;
}
关于C 从函数返回字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22269282/