You have a problem here between using arrays and pointers.
char *f_name;
Here you declared a pointer with no set value. When it does:
fgets(f_name, 100, stdin);
The fgets()
expects to receive in the first argument a pointer pointing to some memory with at least 100
bytes. The first is the pointer to your buffer and the second is the size of it. When you passed an uninitialized pointer, it is causing fgets()
to write somewhere unknown in memory, causing your crash .
The solution, as Maniero said, is to create an array with 100
chars at the beginning, like this:
char f_name[100];
When it does:
fgets(f_name, 100, stdin);
You are now passing a pointer to the first element of array (writing f_name
in this case is equivalent to &f_name[0]
). You have effectively passed a pointer to a buffer of 100
bytes, everything will work. Except ...
f_name = argv[1];
Here f_name
is an array , and setting the arrays value is illegal. That does not even make much sense. What you really want is to copy the data that is in argv[1]
to the array . To do this, use strncpy
, like this:
strncpy(f_name, argv[1], 100);
The function will copy up to 100
bytes from the source to the destination.