Reputation: 75
I'm a CS student about to start my second year. In preparation, I'm reading "An Introduction to C Programming for Java Programmers" by Mark Handley.
In it I found this code, that I decided to try out for myself:
#include <stdlib.h>
main()
{
char *s1;
char s2[80];
char *s3;
s1 = "Hello";
s3 = malloc(80);
printf("Enter your first name:\n");
fgets(s2, 80, stdin);
printf("Enter your last name:\n");
fgets(s3, 80, stdin);
printf("%s %s %s\n", s1, s2, s3);
free(s3);
}
I get the following errors when trying to compile with GCC:
strings.c: In function ‘main’:
strings.c:11: warning: incompatible implicit declaration of built-in `
`function ‘printf’
strings.c:12: error: ‘stdin’ undeclared (first use in this function)
strings.c:12: error: (Each undeclared identifier is reported only once
strings.c:12: error: for each function it appears in.)
Like I said, this is code copied right from the text, so I'm a little frustrated it doesn't work. I figure this must do with the version of GCC. If anyone could help me move in the right direction to understand what is going on here, I would appreciate it. Thanks!
Update: Changed the code per the helpful suggestions below, and it works. It didn't explicitly say to try this code in the text, I took it upon myself to do that. I think the author just intended to show how strings can be handled in C, and how that is different from Java. Thanks everyone, I really appreciate it!
Upvotes: 1
Views: 1500
Reputation: 16607
1. Include header <stdio.h>
(in which printf
, fgets
are defined)
2. main()
-> int main(void)
or int main(int argc, char **argv)
3. add return 0;
(indicating success and a good practice).
Upvotes: 3
Reputation: 6088
Your code relies on an implicit declaration of printf
, fgets
, and stdin
, and an old signature for main()
. It doesn't compile because it's not currently valid C (it's not even valid C89, the first C standard).
You need to include stdio.h
where these definitions are located. GCC allows you to use that signature for main()
as an extension, but it's still not technically valid C.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *s1;
char s2[80];
char *s3;
s1 = "Hello";
s3 = malloc(80);
printf("Enter your first name:\n");
fgets(s2, 80, stdin);
printf("Enter your last name:\n");
fgets(s3, 80, stdin);
printf("%s %s %s\n", s1, s2, s3);
free(s3);
return 0; /* not necessary, but it's good practice */
}
Upvotes: 2