1

您好,我正在自学 C 并阅读 K&R 书籍,但遇到了一些麻烦(我正在运行 OS X)。这来自第 1.5.1 节“文件复制”,它应该将一个字符作为输入,然后输出该字符。这是代码:

#include <stdio.h>

/* --  Copy input to output -- */ 
int main(void)
{
int c;

c = getchar();

while ( c != EOF ) {
    putchar(c);
    c = getchar;
}


}

所以,我认为我的问题不在于代码本身,而在于编译和运行。首先,编译时出现以下错误

/Volumes/Goliath/Dropbox/C programs/prog1_5_1.c: In function ‘main’:
/Volumes/Goliath/Dropbox/C programs/prog1_5_1.c:12: warning: assignment makes integer from pointer without a        cast
/Volumes/Goliath/Dropbox/C programs/prog1_5_1.c:16: warning: control reaches end of non-void function

然后当我运行输出文件(在终端中)它有一个小空间,然后当我输入一个字母时,说我输入

一种

然后我点击返回

我得到了一条新线路。如果我然后按下一个新键,屏幕就会开始变得疯狂,到处都是问号。

我不确定我是否说得通,但我发现这是一个奇怪的问题。非常感谢您提前

4

3 回答 3

5

The second assignment should be c = getchar();. By leaving out the parentheses, you're assigning the address of the getchar function to c, which is very much not what you want.

Also, at the end of main you need the line return 0; or similar in order to get rid of the "control reaches end of non-void function" warning.

于 2011-05-09T01:58:08.790 回答
2

you missed the () on getchar on line 12. without parenthesis, "getchar" evaluates to the address of the function, which is why you get the pointer-cast-to-int warning

于 2011-05-09T02:00:56.610 回答
1

You're missing parenthesis after the 2nd getchar.

This means you're assigning the location in memory of the method to the variable c, which causes an infinite loop as it's never equal to EOF.

于 2011-05-09T01:57:44.690 回答