我正在学习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;
}
答案 0 :(得分:1)
你的想法几乎是正确的,因为
'\0'
复制到reversed
字符串的开头。scanf()
进入无效指针您正在反向进行分配,即代替
normal[i] = reversed[n - i];
必须是
reversed[n - i - 1] = normal[i];
/* ^ you should start at the n - 1 position, and '\0'
* should be at position n.
*/
试试这个
#include <stdio.h>
#include <string.h>
int main() {
char normal[100]; // initialize the original string
char reversed[100]; // declare reversed string
printf("Give me a word.\n"); // ask for user input
if (scanf("%99s", normal) != 1) // retrieve input, set variable
return -1;
int n = strlen(normal); // retrieve length of string
for (int i = 0 ; i < n ; i++) {
/* for i in the original string, the reversed string
* equals n minus i, to reverse the string one by one
*/
reversed[n - i - 1] = normal[i];
}
reversed[n] = '\0';
// print the newly reversed string
printf("%s\n", reversed);
return 0;
}
答案 1 :(得分:1)
你取消引用一个狂野的指针:
char* normal; // uninitialized, points to random location
scanf("%s", &*normal); // write to random location (at best)
&*
顺便说一下没有效果。因此,从此处发生的任何其他事情都是未定义的。
要解决这个问题,你可以写:
char normal[10];
scanf("%9s", normal);
然后你的循环继续并从reverse
(空白)复制到normal
。您可能打算从normal
复制到reverse
。赋值运算符为destination = source
。
最后,你的循环(如果你做了那个修复)从normal[strlen(normal)]
开始,它是空终止符。您需要检查n > 0
,然后从i = n-1
开始。
答案 2 :(得分:0)
这应该适合你:
#include <stdio.h>
#include <string.h>
#define SIZE 30
int main() {
char normal[SIZE+1], reversed[SIZE+1];
int n = 0, i = 0;
printf("Give me a word.\n");
fgets(normal, SIZE, stdin);
//^ Reads in the text
n = strlen(normal);
for(i = n-1; i >= 0; i--)
reversed[n-i-1] = normal[i];
//^ Changed, also note that the index starts with 0
reversed[n] = '\0';
//^ End string
printf("%s\n", reversed);
return 0;
}