#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int a;
char c[1];
printf("\n%d\n", a);
gets(c);
printf("\n%d\n", a);
return 0;
}
When reading c using gets the value of a, printed previously, is printed as having the value: 0; when using scanf("%c", &c); as a replacement for gets(c); the value of a stays the same throughout the code.
I can't seem to figure out why this is, could someone please explain how this is possible?
You only have room for
\0in the stringaandgets()does not care that there is not enough room. It evidently overwrote parts of memory resulting in your problem. Instead ofgets(), usefgets().C standard (2011) has removed
gets()from its specification.OP: ... when using
scanf("%c",&c);as a replacement forgets(c);the value ofastays the same throughout the code.This is good as
scanf("%c",&c);should not affecta.If you are hoping for some overwriting of
adue to a smallcby usinggets(c);, you may trychar c[1]; int a;, but any such code invokes undefined behavior.