Reputation: 13
I'm learning C. When I use this code on Linux I didn't get this kind of error. Can you show me how to fix it? I've tried many solutions but nothing worked T_T. Thanks in advance.
Here's the code
#include <conio.h>
#include <stdio.h>
void main()
{
int a;
float x;
char ch;
char* str;
printf("Enter integer number: ");
scanf("%d", &a);
printf("\nEnter real number : ");
scanf("%f", &x);
printf("\nEnter a character: ");
fflush(stdin);
scanf("%c", &ch);
printf("\nEnter a string: ");
fflush(stdin);
scanf("%s", str);
printf("\nData:");
printf("\n Integer: %d", a);
printf("\n Real: %.2f", x);
printf("\n Character: %c", ch);
printf("\n String: %s\n", str);
}
Upvotes: 0
Views: 2894
Reputation: 311068
For starters this call
fflush(stdin);
has undefined behavior. Remove it.
Secondly in this call of scanf
scanf("%c", &ch);
you should prepend the conversion specifier with a space
scanf(" %c", &ch);
^^^^^
Otherwise white space characters as the new line character '\n' will be read.
The pointer str
is not initialized and has an indeterminate value
char* str;
So this call
scanf("%s", str);
invokes undefined behavior.
You should declare a character array as for example
char str[100];
and call the function scanf like
scanf("%99s", str);
Upvotes: 1
Reputation: 169277
A bare char *str;
does not point to any valid memory, so you can't scanf()
a string into it.
Either allocate some memory on the stack, e.g. char str[512];
, or dynamically with malloc()
and friends.
Upvotes: 0