Bill Cunningham wrote:
Get a good C book - Kernighan and Ritchie, The C Programming Language,
2nd Edition, is old but well worth the money.
Well done for including this.
This should be int main(void)
A 'char *' is a pointer-to-char. It can also point to the first char in
a char array - and so, using sloppier language, point to an
array-of-char. But here it doesn't point to anything.
A 'char *' is a way of accessing chars, but in this program you have no
chars to access.
> printf("Enter code-> ");
> fflush(stdout);
> fgets(cap,100,stdin);
Well done on not using gets().
But now the problem becomes apparent. fgets() does not provide the chars
you need to write to. You provide a 'char *' to fgets() which points to
the chars which /you/ have to provide. Here you haven't provided
anything - so fgets() has no allocated memory to write to.
This should be:
printf(cap);
return 0;
}
Now, a question which you should be asking is: "If fgets() is writing to
chars which don't exist or haven't been allocated, why did my program work?"
The answer is that there exist certain programs which break the rules of
C, and when that happens the C standard places no restriction on the
program behaviour. This is known as "Undefined behaviour". What that
means is your program may work perfectly - or it may output subtly wrong
answers, or crash, or slowly eat up all your memory, or anything it
likes. If you compile the same C program on a different compiler you may
find it doesn't work. It may even crash on a new version of the same
compiler!
This means that learning C by trial-and-error alone is a Bad Idea; just
because a program compiles and runs as expected, doesn't mean that it is
valid C.
This is why the first sentence in this post was "Get a good C book".