如何解决我的反向数组在 C 中添加随机字符是什么
我在 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);
}
解决方法
函数 inputtoarray
没有输入字符串。结果这个循环
for (cinput=0; input1[cinput] != '\0'; ++cinput){
}
在函数 reverseinput
内导致未定义的行为。
函数inputtoarray
可以通过以下方式查找
void inputtoarray( char input[],size_t n )
{
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
size_t i = 0; //i is the array counter
//ask the user to type in a word
printf("Please type in a word:\n");
for ( ; i + 1 < n && ( c = getchar() ) != EOF && c != '\n'; ++i )
{
input[i] = c;
}
input[i] = '\0';
}
并称为喜欢
inputtoarray( input,MAXLINE );
此外这个循环
for (cinput=0; coutput > 0; --coutput,++cinput ){
temp[coutput] = input1[cinput];
//input1[coutput] = temp[coutput];
//printf("%s",temp);
}
由于条件 temp[0]
而未设置元素 coutput > 0
。所以数组 temp
的第一个元素有一个不确定的值。
还有这个任务
input1 = temp;
没有意义,因为它改变了局部变量input
,而不是改变了指针(参数)input
指向的数组。
不使用标准字符串函数,程序看起来如下所示。
#include <stdio.h>
#define MAXLINE 80
void inputtoarray( char input[],size_t n )
{
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
size_t i = 0; //i is the array counter
//ask the user to type in a word
printf("Please type in a word:\n");
for ( ; i + 1 < n && ( c = getchar() ) != EOF && c != '\n'; ++i )
{
input[i] = c;
}
input[i] = '\0';
}
void reverseinput( char input[] )
{
size_t n = 0;
while ( input[n] ) ++n;
if ( n != 0 )
{
for ( size_t i = 0; i < --n; i++ )
{
char c = input[i];
input[i] = input[n];
input[n] = c;
}
}
}
int main(void)
{
char input[MAXLINE];
inputtoarray( input,MAXLINE );
reverseinput( input );
puts( input );
return 0;
}
它的输出可能看起来像
Please type in a word:
Hello
olleH
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。