在复制函数的最后一行中,我在复制的字符串末尾存储了一个'\0',这不是最初在代码中存储的。
include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int getline(char line[ ], int maxline);
void copy(char to[ ], char from[ ]);
/* print longest input line*/
int main()
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /*current input line*/
char longest[MAXLINE]; /* longest line saved here */
max=0;
while ((len=getline(line, MAXLINE)) > 0)
if (len > max)
{
max=len;
copy(longest, line);
}
if (max>0) /* there was a line*/
printf("%s", longest);
return 0;
}
/* getline: read a line into s, return length */
int getline(char s[ ], int lim)
{
int c,i;
for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i]=c;
if(c=='\n')
{
s[i]=c;
++i;
}
s[i]='\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i=0;
while((to[i]=from[i])!='\0')
++i;
to[i] = '\0'; /*<-----Problematic Area*/
}我在这里的问题是,复制的字符串是否在末尾已经包含了'\0‘。如果不是这样,那么像我在代码中所做的那样,包括它是否是一个好的实践。
发布于 2018-10-16 18:52:10
声明
while ((to[i] = from[i]) != '\0')
++i;首先将from[i]的值分配给to[i],然后将赋值与\0进行比较--如果刚刚复制的是null终止符,则循环结束。
因此
to[i] = '\0';是没有必要的,但在这里不是不正确的。
但是,使用不必要的代码并不是很好的风格,因为它会使重构和其他代码的推理变得更加困难。仅仅是最后一个赋值的存在,就会使未来的读者感到困惑,认为循环本身不足以正确终止字符串。
另外,如果有人来编辑代码
while ((*to++ = *from++));正如WhozCraig所建议的那样,他们可能会错误地认为他们确实需要添加空终止符,这一次可能会超出界限:
*to++ = 0;https://stackoverflow.com/questions/52842110
复制相似问题