gpt4 book ai didi

c - 在 C 中反转数组

转载 作者:太空宇宙 更新时间:2023-11-04 05:07:39 25 4
gpt4 key购买 nike

我是 cpp 新手,对数组有疑问。我下面的代码应该创建 str 的反向版本并将其存储在 newStr 中。但是, newStr 总是空的。有人可以向我解释为什么即使我将 str 中的值赋给它也会发生这种情况吗?

void reverse (char* str) {
char* newStr = (char*)malloc(sizeof(str));

for (int i=0;i<sizeof(str)/sizeof(char);i++) {
int index = sizeof(str)/sizeof(char)-1-i;
newStr [i] = str [index];
}
}

PS:我知道通过移动指针或使用 std::reverse 函数来反转数组的效率要高得多,但我对为什么上面的代码不起作用很感兴趣。

最佳答案

正如上面评论者指出的那样,sizeof(str) 不会告诉您字符串的长度。你应该使用 size_t len = strlen(str);

void reverse (char* str) {
size_t len = strlen(str);
char* newStr = (char*)malloc(len + 1);

for (int i=0; i<len;i++) {
int index = len-1-i;
newStr[i] = str[index];
}
newStr[len] = '\0'; // Add terminator to the new string.
}

不要忘记释放malloc的任何内存。我假设您的函数将返回您的新字符串?

编辑:+1 长度,为终结符腾出空间。

关于c - 在 C 中反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com