gpt4 book ai didi

c - K&R getline : --lim > 0 or lim-->0? 的 ANSI C 编程

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

在 K&R 的 ANSI C 编程的第 69 页上,有一个函数示例,该函数用作特殊版本的 Unix 程序 grep。

代码是:

#include <stdio.h>
#define MAXLINE 1000 //max input length
int getline(char line[], int max);
int Strindex(char source[], char searchfor[]);
char pattern[] = "ould";

int main()
{
char line[MAXLINE];
int found =0;

while (getline(line,MAXLINE) > 0)
if (Strindex(line, pattern)>=0){
printf("%s", line);
found ++;
}
return found;
} // end of main function


int getline (char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0 && (c=getchar()) != EOF && c!= '\n')
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}


int Strindex (char s[], char t[])
{

int i,j,k;
for (i =0; s[i] != '\0'; i++)
for (i =i, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return i;

}
return -1;

} // end of strindex

是不是报错了:--lim > 0?如果 MAXLINE 在我的例子中将是 1,我将在 while 0>0 的开头得到 - False,我不会得到任何字符串?

最佳答案

是的,你是对的也是错的。您将得到一个空的 NUL 终止字符串(lim 应该包含终止 NUL 字符)。一个有效的 C 字符串应该以 NUL 结尾,即使是零长度的字符串也至少包含一个字符。因此,如果您的 MAXLINE 为 1,则它已经满了,无法容纳更多字符。

while (--lim > 0 && (c=getchar()) != EOF && c!= '\n')
s[i++] =c;
if (c =='\n')
s[i++] =c;
s[i] = '\0' ;

最后一条语句 s[i] = '\0' 分配 NUL 字符,在您的情况下是 s[0] = '\0';。此外,getline 函数在下一条语句 return i; 中正确返回捕获字符串的长度 (=0)。

关于c - K&R getline : --lim > 0 or lim-->0? 的 ANSI C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27677631/

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