This function is a problem:
void input(char* a)
{
char buff[8];
scanf("%s", buff);
*a = buff;
}
buff
is local variable that is only valid while input()
is running, so
returning this variable is wrong.
*a = buff;
is also wrong. *a
is the same as a[0]
, that means it is a
char
. buff
is an array of char
, so you are assigning a pointer to an array
of char
to a char
variable. That doesn't sound right, it's putting apples in
the oranges box. In fact what is happening is that you are assigning the address
pointed to by buff
in the memory pointed to by a
.
Your compiler should have warned you about that, don't ignore the
compiler warnings, they are there to help you, not annoy you,
void input(char *a)
{
scanf("%s", a);
}
would be the correct function.
Doing
char name[8];
input(&name);
is wrong, even though the address of name
and &name
will be the same, but
they will have different types. name
decays into a pointer, so it is a
char*
. However &name
is a pointer to an array of char
, a different type.
The compiler should give you a warning like this:
warning: passing argument 1 of bar
from incompatible pointer type
note: expected char *
but argument is of type char (*)[8]
The correct call is:
input(name);
In general there is one big problem, though: You only declare 8 spaces for the
buffer. If the name is longer than 7 characters, you will have a buffer
overflow. Instead of using scanf
I recommend using fgets
instead, because
here you have much more control of the input and the memory boundaries.
char name[30];
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = 0; // removing possible newline
scanf
is not always easy to use. A name can be long and have spaces in it.
Specially for a beginner, this can be tricky. fgets
is easier to use.