So I can’t really figure out why scanf is messing up a[0]. When I print out the array, a[0] is empty and where I want a[0] it is stored in a[1].
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *a[128];
int i;
int num;
scanf("%d", &num);
for (i = 0; i < 2; i++) {
a[i] = malloc(50*sizeof(char));
fgets(a[i], 100, stdin);
}
printf("[0] = %s [1] = %s", a[0], a[1]);
return 0;
}
Your
scanf()is not messing up youra[0], at least not in the way you seem to think, by somehow corrupting its storage area. This is very much an issue with mixing different "methods" of input.What is actually happening with your
scanf/fgetscombo is that thescanfis getting the integer, but not reading the newline that you enter at the end of that number, so the firstfgetspicks that up.The ISO standard states it thus (in the specified sequence):
That first and last paragraph is important. The first means the leading whitespace is skipped, the last means that trailing whitespace is left in the input stream to be read later.
However, I’ll tell you what may mess it up (depending on the lengths of your input lines), it’s the fact that you allocate 50 characters space for each
a[i]then read up to 100 characters into it. Thats undefined behaviour right there.If you want a robust input solution that handles buffer sizes correctly, detects lines that are too long, throws away the remainders of those lines and so on, see this answer.
Alternatively, if you want to emulate line-based behaviour with the non-line-based
scanf(and you’re sure that your lines are always less than 100 bytes), you can change:into:
so that it grabs and throws away the rest of the line.
And you should ensure that the maximum-size argument to
fgetsmatches the amount of memory available (such as by usingsizeofin the above code).One other thing, please don’t complicate code by multiplying things by
sizeof(char)– that value is always 1 as per the standard.