I'm using xCode because I found the debugger to be very useful. So in the debugger I see, after I enter the students name name[0] = \0 no matter what. But then the rest of the name will be correct. For example, if I put John, it will come back saying \0, o, h, n. Help please?
char name[MAX_NAME_LENGTH];
char department[MAX_DEPT_LENGTH];
int rank;
int empty = 0;
printf("\nPlease enter the students name: ");
scanf("%s", &name);
printf("\nPlease enter the students department: ");
scanf("%s", &department);
printf("\nPlease enter the students rank: ");
scanf("%d", &rank);
strcpy(studentArray[empty].name, name);
strcpy(studentArray[empty].department, department);
studentArray[empty].rank = rank;
Do this:
Note the absence of ampersands in the first two calls to
scanf
. This is because the compiler implicitly convertsname
anddepartment
into pointers to the first elements of the respective arrays (&name[0]
,&department[0]
) when they are used in an expression (there are expections to this rule, see here for details).Read this for further reference.
use
scanf("%s", name);
avoid using &, it's too easy to get wrong.
Your variables
name
anddepartment
are character arrays (char (*)[]
). When you pass these variables to printf/scanf (or any other function, arrays are passed by reference), their types decay toTYPE*
(in your casechar*
) and are passed as the memory location of the first element in the array.When you try to pass the address of the varible (
&name
), you are passing a pointer to that variable's memory location (in your case, this decays tochar(*)[0]
). This question intrigued me becausename
and&name
will have the same value, but different types. Since printf/scanf are defined to receivechar*
, passing char(*)[] results in undefined behavior - some compilers will handle if for you while others won't (VS2010 and maybe earlier versions handle this for you).I was close, but had some help with this answer (learned a lot): & operator definition for arrays in C. If they provide an answer here, I'll delete mine.
When you declare an array;
name
without an index is a pointer to the first element in the array.When a function (such as
scanf()
) calls for achar *
it wants the pointer to the first element.The scanf function needs to know the address in memory it needs to read in, so for things like integers
is correct. But things like name are already addresses (the name of an array is effectively the address of its first element) so instead of :
you want:
And similarly for other arrays.
You need to use
scanf("%s", name);
instead ofscanf("%s", &name);
(same fordepartment
).scanf
needs a memory address to write to. In case of a string it expects achar *
and passing achar[]
is fine in this case (it is vulnerable to buffer overflows though!).However, for your integer - which is not a pointer - you need to pass the memory address of the integer, i.e.
&rank
instead ofrank
- which you already did.