1

Hello I am teaching myself C and going through the K & R book and I am having some trouble (I am running OS X). This is from section 1.5.1 "File Copying" which is supposed to take a character as input, then output the character. Here is the code:

#include <stdio.h>

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

c = getchar();

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


}

So, I think my problem is not with the code itself but with compling and running. First of all, when compiling I get the following errors

/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

Then when I run the output file (in terminal) it has a small space, then when I input a letter, say I type

a

then I hit Return

and I get a new line. If I then hit a new key, the screen starts going crazy with question marks all over the place.

I am not sure if I am making much sense but I am finding this an odd problem to have. Thank you very much in advance

Guillermo Alvarez
  • 1,695
  • 2
  • 18
  • 23

3 Answers3

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.

jwodder
  • 54,758
  • 12
  • 108
  • 124
  • Or you can prototype main as being void: `void main(void)` – Mel May 09 '11 at 02:07
  • @Mel: That runs contrary to the C standard. `main` should always return an `int`. – jwodder May 09 '11 at 02:08
  • Yep, true and you get a compiler *warning* about, yet a valid program. When starting C, one should be made aware that there are many ways to screw up. :) – Mel May 09 '11 at 02:15
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

zhaian
  • 109
  • 5
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.

Adam Bryzak
  • 2,608
  • 2
  • 19
  • 7