我需要分配 t2
但我不知 Prop 体如何分配。
char *reverse(char *t)
{
int length= strlen(t);
char *t2 = (char *) malloc(length * sizeof(char*));
for(int i= (length-1);i>=0;i--)
t2[i]=t[length-1];
return t2;
}
有什么帮助吗?
最佳答案
你很接近。
char *t2 = malloc(length + 1); // reserve space for a null terminator
不过,您可能希望该循环从 length
开始,而不是 length - 1
。循环内的分配也是错误的(您只更改目标位置,而不是源)。确保在返回之前以 null 终止字符串。
编辑说明:
- 您不需要在 C 程序中强制转换
malloc()
的返回值。 sizeof(char)
是1
- 不需要相乘。- 根据您正在寻找的语义,您可能根本不需要
malloc()
。字符串反转可以在 C 中就地完成。
关于c - 在 C 中返回反转字符串的函数 - 分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15232534/