与fgets实现(K&安培; R) [英] fgets implementation (K&R)
问题描述
我是新来编程,启动了与Objective-C的,但已经决定回到基础进一步进展之前。我花基于C一段时间,我通过指针混乱中挣扎。我的问题是关于如何K&放大器;(P165,第二版)低于code R表示与fgets实施是从一对夫妇的我的意见的文本直接。
I'm new to programming, starting off with Objective-C but have decided to go back to basics before progressing further. I'm spending some time on C, and am struggling through pointer confusion. My question is about how K&R says fgets is implemented (p165, 2nd ed.) Code below is direct from the text with a couple of my comments.
char* fgets(char* s, int n, FILE *iop)
{
register int c;
register char* cs;
cs = s;
while(--n > 0 && (c = getc(iop)) != EOF)
{
// put the input char into the current pointer position, then increment it
// if a newline entered, break
if((*cs++ = c) == '\n')
break;
}
*cs = '\0';
return (c == EOF && cs == s) ? NULL : s;
}
1)我们通过一个char * s到的与fgets功能,在其位置,我们存储用户输入。为什么有必要宣布当地的char * CS - ,然后将其初始化为s?为什么我们不能直接操作/ if语句中添加送?眼看因为CS被初始化为S点,不添加字符到CS完全一样的东西?
1) We pass a char* s to the fgets function, at whose location we store the user input. Why is there a need to declare the local char* cs - and then initialise it to s? Why can't we directly manipulate/add to s within the if statement? Seeing as cs is initialised to point s, isn't adding the chars to cs exactly the same thing?
2)系杆中与上述...在函数返回时,进行测试以查看是否CS ==第为什么这个必要吗?
2) Tied in with the above...When the function returns, a test is made to see if cs == s. Why is this necessary?
我想我可能失去了一些东西很基本的 - 我这样做了检查和谷歌,但不能完全弄明白。谢谢!
I think I may be missing something very fundamental - I did check SO and Google but can't quite figure it out. Thanks!
推荐答案
这是因为在最后一行的检查, CS ==小号
。这种比较将修改指针 CS
,对原来的取值
来看看,如果我们读过的任何字符。如果我们没有那么我们就返回NULL。
It's because of the check on the last line, cs == s
. This comparison checks the modified pointer cs
against the original s
to see if we've read any character. If we haven't then we return NULL.
通过使用 CS
整个原始指针取值
是preserved。如果取值
进行直接操作( * S ++
而不是 * CS ++
),那么我们就必须找到另一种方式来检查任何字符是否阅读。
By using cs
throughout the original pointer s
is preserved. If s
were directly manipulated (*s++
instead of *cs++
) then we'd have to find another way to check whether any characters were read.
我们也可以认为这是一个很好的做法,独自离开函数的参数,并把它们作为常量
。一些程序员采用这种做法,以此来提高code清晰。
One can also argue that it's a good practice to leave function parameters alone and treat them as const
. Some programmers follow this practice as a way to enhance code clarity.
这篇关于与fgets实现(K&安培; R)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!