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.
Because you're passing uninitialized values into scanf as pointers. Try
scanf("%c %c %c %c %c", &first, &second, &third, &fourth, &fifth);
Quick Solution.
Because you are passing char-variables to scanf
instead of pointers.
scanf("%c %c %c %c %c", &first, &second, &third, &fourth, &fifth);
Rule of Thumb.
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
- Pass the address of the variable you want to write into.
and
- The type of the target must match exactly the specification of the format tokens,
About the latter: E.g., you are screwed if you pass a double-pointer for the %d
format token.
Prevention.
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)));
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);
精彩评论