- 论坛徽章:
- 0
|
C语言中的字符串结尾如果不加\0,用printf %s打印是不是会一直打印到超出字符串的范围到某个未知字符?在Windows XP SP2下用cygwin练习, 同样一个程序,字符串结尾不加\0会多打印一些没规律的字符.
The C Programming Language SECOND EDITION中1.9 Character Arrays 中的程序:
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* print the longest input line */
main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max)
{
max = len;
copy(longest, line);
}
if (max > 0)
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;
}
|
其中getline函数中,如果s[lim-1]为\n的话,那么最后的\0就写到字符串外了.我分析的对不对?
另外帖子编辑中的插入代码似乎有些问题,代码中注释前的UBB代码为[color=#FF9900>,还要手动编辑一下.
[ 本帖最后由 ibmwebzh 于 2007-7-6 12:24 编辑 ] |
|