You have a problem here between the use of arrays and pointers.
char *f_name;
Here declared a pointer with no defined value. When 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, you are doing the fgets()
write somewhere any unknown memory, causing your crash.
The solution, as Maniero said, is to create a array with 100
chars right at the beginning, so:
char f_name[100];
When does:
fgets(f_name, 100, stdin);
You are now passing a pointer to the first element of array (write down f_name
in that case is equivalent to &f_name[0]
). You effectively passed a pointer to a buffer of 100
bytes, everything will work. Except...
f_name = argv[1];
Here f_name
is a array, and set the value of arrays is illegal. It doesn’t even make much sense. What you really want is to copy the data that is on argv[1]
to the array. For that use the strncpy
, thus:
strncpy(f_name, argv[1], 100);
The function will make the copy of up 100
bytes from source to destination.
Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?
– Maniero