【发布时间】:2021-04-09 22:31:19
【问题描述】:
我在 C 中编写了反转数组的代码。 我正在使用 C17。在代码中要求用户输入一个单词,然后将该单词放入一个数组中 然后反转。 该代码适用于它添加一些随机字符的异常,我无法弄清楚它为什么这样做。
你能帮我解决这个问题吗?
这是我的代码
#include <stdio.h>
#define MAXLINE 80
void inputtoarray(char input[]); //Take the input from user and put it into an array
void reverseinput(char input1[]);
int main(){
char input[MAXLINE];
inputtoarray(input);
reverseinput(input);
return 0;
}
void inputtoarray(char input[]){
int c; //to hold the indiviual characters before going into the array
//int was used over char because I want to be able to hold EOF
int i; //i is the array counter
//ask the user to type in a word
printf("Please type in a word:\n");
for(i=0; (c=getchar()) != '\n'; ++i){
input[i] = c;
}
}
void reverseinput(char input1[]){
int cinput;
int coutput;
char temp[MAXLINE]; //define a temporary array
//count the number of characters in the array
for (cinput=0; input1[cinput] != '\0'; ++cinput){
}
coutput=cinput;
//the reversing process. Here cinput holds the number of the last character
for (cinput=0; coutput > 0; --coutput, ++cinput ){
temp[coutput] = input1[cinput];
//input1[coutput] = temp[coutput];
//printf("%s", temp);
}
input1 = temp;
printf("%s", input1);
}
【问题讨论】:
-
你没有用
\0终止input -
请提供输入、预期输出和实际输出,以便我们有一个示例,我们知道您的测试将无法正常工作
-
看看你的代码;你在哪里为你的输入添加一个 NUL 终止符? (提示:你没有)。传递长度通常比依赖 '\0' 更安全
-
@IrAM 我将如何以 \0 终止
-
@TheGrandJ 例如,如果你运行代码并输入 hello 你会得到 `olleh
标签: arrays c reverse c-strings function-definition