Reputation: 1
int main() {
char first,second,third,fourth,fifth;
scanf("%c %c %c %c %c",first,second,third,fourth,fifth);
printf("%c%c%c%c%c",first,second,third,fourth,fifth);
getch();
return 0;
}
The above program is compile without any error (GNU GCC) but on execution minimizes the 'current window' and terminates again without any error. Why?
Update
int main() {
char first,second,third,fourth,fifth;
scanf("%c %c %c %c %c",&first,&second,&third,&fourth,&fifth);
printf("%c%c%c%c%c",first,second,third,fourth,fifth);
getch();
return 0;
}
The above code is the changed after the answers received, but still behaves the same way, just that the compiler does throw any error or even warnings this time.
Upvotes: 0
Views: 372
Reputation: 48686
When using scanf, you must preface each variable with an Ampersand symbol because you must pass in a pointer to a non-pointer variable, not just a variable itself, like so:
scanf("%c %c %c %c %c",&first,&second,&third,&fourth,&fifth);
Upvotes: 2
Reputation: 39089
Because you are passing char-variables to scanf
instead of pointers.
scanf("%c %c %c %c %c", &first, &second, &third, &fourth, &fifth);
icemanind mentioned that "When using scanf, you must preface each variable with an Ampersand", but that is too broad. If you stricly follow that rule, you might be passing pointers-to-pointers-... . Instead, as rule of thumb, you must
and
About the latter: E.g., you are screwed if you pass a double-pointer for the %d
format token.
If you had used compiler warnings, in your specific case -Wformat
, but in the general case just use -Wall
(and preferably -Wextra
, too), the compiler would have warned you:
gcc -Wall -Wextra foo.c
warning.cc: In function `int main()':
warning.cc:4: warning: format argument is not a pointer (arg 2)
warning.cc:4: warning: format argument is not a pointer (arg 3)
warning.cc:4: warning: format argument is not a pointer (arg 4)
warning.cc:4: warning: format argument is not a pointer (arg 5)
warning.cc:4: warning: format argument is not a pointer (arg 6)
For the curious: This warning is based on a compiler extension that targets format strings (see gcc's list of attributes:
The format attribute specifies that a function takes printf, scanf, strftime or strfmon style arguments which should be type-checked against a format string. For example, the declaration:
extern int
my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
Upvotes: 2
Reputation: 34408
Because you're passing uninitialized values into scanf as pointers. Try
scanf("%c %c %c %c %c", &first, &second, &third, &fourth, &fifth);
Upvotes: 2