gpt4 book ai didi

c - 为什么这个程序不反转字符串?

转载 作者:行者123 更新时间:2023-11-30 20:14:00 25 4
gpt4 key购买 nike

我正在学习 C。我编写了以下程序来尝试反转用户输入的字符串。然而,这不起作用。我想知道为什么。

这是带注释的代码:

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv) {
char* normal; // initialize the original string
printf("Give me a word.\n"); // ask for user input
scanf("%s", &*normal); // retrieve input, set variable
int n = strlen(normal); // retrieve length of string
char reversed[10] = {0}; // declare reversed string

// for loop starting from n length, decrementing by one
for(int i = n; i >= 0; i--) {
/* for i in the original string, the reversed string
equals n minus i, to reverse the string one by one */
normal[i] = reverse[n - i];
}

// print the newly reversed string
printf("%s\n", reversed);

return 0;
}

最佳答案

取消引用野指针:

char* normal; // uninitialized, points to random location

scanf("%s", &*normal); // write to random location (at best)

顺便说一句,&* 没有任何效果。因此,从这里开始发生的任何其他事情都是未定义的。

要解决此问题,您可以编写:

char normal[10];
scanf("%9s", normal);

然后你的循环继续并从reverse(空白)复制到normal。您可能想从正常复制到反向。赋值运算符是 destination = source

最后,您的循环(如果您进行了修复)从 normal[strlen(normal)] 开始,它是 null 终止符。您需要检查 n > 0,然后从 i = n-1 开始。

关于c - 为什么这个程序不反转字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182074/

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