gpt4 book ai didi

c - 这段代码有什么问题?试图显示复制的字符数组行

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:46 25 4
gpt4 key购买 nike

我只是简单地尝试复制输入的行并将其显示在屏幕上但是,输出仍然包含一些额外的术语......有什么问题吗?

#include<stdio.h>
#define MAXLINE 1000

void copy(char to[], char from[]);

main()
{
int length;
int limit;
char saved[MAXLINE];
char len[MAXLINE];

copy(saved,len);

printf("%s", saved);
}

void copy(char to[],char from[])
{
int a,i,c;

i = 0;
a = 0;

while((c = getchar()) != EOF)
{
from[i] = c;
++i;
}

while((to[a] = from[a]) != EOF)
++a;
}

最佳答案

调用printf()期待一个以 null 结尾的字符串,但是 copy()函数不提供。

更改 copy() 中的第一个循环这样数组索引i检查,以避免缓冲区溢出,然后在循环终止后添加一个空终止符:

// check array index
while(i < MAXLINE-1 && (c = getchar()) != EOF)
{
from[i] = c;
++i;
}

// add null-terminator to from[]
from[i] = '\0';

然后更改第二个循环,使其在遇到空终止符时终止,并添加 \0to[]结尾的字符:

// change loop termination condition
while((to[a] = from[a]) != '\0')
++a;

// add null-terminator to to[]
to[a] = '\0';

更好,使用 i 的保存值终止循环,并复制 \0来自 from[]to[] :

// better, use i to terminate loop
for (a = 0; a <= i; a++)
to[a] = from[a];

在上述循环的第一个版本中,我无意中使用了 for (a = 0; a < i; a++) {} , 被@alk 捕获了。此循环无法复制最终的 \0性格,从什么时候开始a == i ,循环终止而不执行主体。上面的快速修复,更改 a < ia <= i有效,但循环不再是惯用的(因此我最初的麻烦;我通过反射在循环中写 a < i)。一个可能更好的解决方案是增加 i\0之后字符存储在 from[] 中,就像对 from[] 中的所有其他字符所做的一样.这在下面的最终代码中进行了说明。

此外,请注意 main() 的函数签名应该是 int main(void) , 自 copy()声明为返回 void , 应该没有值 return在函数末尾编辑。而且,为了真正正确,数组索引的类型应该是 size_t ,这是一个 unsigned保证能够容纳任何数组索引的整数类型。

#include <stdio.h>

#define MAXLINE 1000

void copy(char to[], char from[]);

int main(void)
{
// int length;
// int limit;
char saved[MAXLINE];
char len[MAXLINE];

copy(saved,len);

printf("%s", saved);

return 0;
}

void copy(char to[],char from[])
{
size_t a,i;
int c;

i = 0;
a = 0;

// check array index
while(i < MAXLINE-1 && (c = getchar()) != EOF)
{
from[i] = c;
++i;
}

// add null-terminator to from[], increment i
from[i] = '\0';
++i;

// use i to terminate copy loop
for (a = 0; a < i; a++)
to[a] = from[a];
}

关于c - 这段代码有什么问题?试图显示复制的字符数组行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45115968/

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