gpt4 book ai didi

c - 程序打印错误输出

转载 作者:行者123 更新时间:2023-12-05 09:04:28 25 4
gpt4 key购买 nike

为什么下面的代码打印的是 !notreblo! 而不是 !notrebloH! 从哪里来?我正在尝试编写一个反转数组的程序,我正在使用 main 函数来测试 rev_string 函数。

#include <stdio.h>

int main(void)
{
char s[11] = "Holberton!";

printf("%s\n", s);
rev_string(s);
printf("%s\n", s);
return (0);
}

void rev_string(char *s)
{
char new[500];
int count, newcount;

count = 0, newcount = 0;

while (*(s + count) != '\0')
{
*(new + count) = *(s + count);
count++;
}

count--;

while (count > 0)
{
*(s + newcount) = *(new + count);
count--;
newcount++;
}
}

最佳答案

第二个 while 不复制第一个字符,因为复制的最后一个字符位于索引 1 处。条件告诉它:count > 0

将其更改为 count >= 0

(+1 是著名的“一次性”错误。如果我每次都能得到 1 美分,我就会成为富人。)

关于c - 程序打印错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68588228/

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