The problem with
scanf("%s", key);
scanf("%s", vector);
is:
key
and vector
are of type char
, not pointers to char
. The can hold one character only.1
- With
%s
scanf
expects a pointer to char
. As it stands right now, you
are passing uninitialized integer values as if it were pointers, that's
undefined behaviour and your program crashes as a result of it. The compiler
must have given you a warning about this, don't ignore the compiler's warnings,
they are there to help you, not annoy you.
The correct version:
char key[101], vector[101];
...
scanf("%s", key);
scanf("%s", vector);
// or to limit the number of bytes
// written in the buffer, as pointed out
// in the comments by user viraptor
scanf("%100s", key);
scanf("%100s", vector);
For more information about scanf
, please read the documentation
Footnote
1A string in C is a sequence of characters that ends with the
'\0'
-terminating byte. A string with one single character needs a char
array
of dimension 2 or more. In general, a char
array of dimension n
can store
strings with maximal length of n-1
. You have to keep that in mind when passing
pointers to char
to functions when they expect strings. A pointer to a single
char
will lead to undefined behaviour because it overflows.