You made a char
pointer. But it's just a pointer and not an array.
If you use a uninitialised pointer, which has some indeterminate (garbage) value, it points to some location which may not even be a location that the program is allowed to access or worse yet could be pointing to another process's memory which would in turn cause error.
Either use dynamic memory allocation like
char *a=malloc(sizeof(char)*100);
if(a==NULL)
{
perror("Not enough space");
}
which must be deallocated after use with free(a)
.
Or make a statically allocated array like
char a[100];
You seem to expect to read a string and then a number. If the input is a string without numbers and then a number, you could use
scanf("%99[^0-9]%d", a, &b);
The scanf()
would read at most 99 characters till it encounters a number, places it in a
and the number is stored in b
.
As @David pointed out, this wouldn't skip the leading white spaces. If you want to skip the leading white spaces before writing to a
, use a space before the %99[^0-9]
like
scanf(" %99[^0-9]%d", a, &b);
Check the return value of scanf()
to see if scanf()
was successful as you did.
Note that if scanf()
fails, some characters will still be left in the input buffer and you may want to remove it.
You could do this to consume from input buffer till the next \n
int ch;
while( (ch=getchar())!='\n' && ch!=EOF );
fscanf(stdin, ........)
is equivalent to scanf(.........)
.