The below code generates an incompatible pointer type error and warning: control reaches end of non-void function in the filename function:
#include <stdio.h>
#include <stdlib.h>
int quit;
char *filename(int *);
int main ()
{
filename(&quit);
return 0;
}
char *filename(int *i1)
{
char input[16];
char *dum=(char*)malloc(16*sizeof(char));
if (dum==NULL){
printf("Memory could not be allocated \n");
}
else {
printf("Memory was allocated – remember to free\n \n");
*i1=1;
fputs("Input filename = ", stdout);
fflush(stdout);
fgets(input,sizeof(input),stdin);
printf("Filename = \"%s\"\n",input);
return i1;
}
}
I'm new to this, can someone help me with this error?
Well, yes? The function is declared to return char *, but you return i1 which is the input argument and has type int *.
You might mean to return the newly allocated string dum, and perhaps also fill it with the data that was read using fgets() to the separate character array input. In this case, you need to copy the data over, and return dum.
It would be more concise, simpler, and generally better to read directly into dum:
fgets(dum, 16, stdin);
return dum;
Note that this duplicates the size of the buffer from the malloc() call, which is a "code smell". This can be improved by making it a local constant in the function:
char * filename(void)
{
const size_t max_fn = 16;
char *dum;
if((dum = malloc(max_fn)) != NULL)
{
if(fgets(dum, max_fn, stdin) != dum)
{
free(dum); /* Input failed, free the buffer and drop the pointer. */
dum = NULL;
}
}
return dum;
}
My latter code also has the benefit that it checks return values of functions that can fail. Both memory allocation (malloc()) and I/O (fgets()) can fail, so you must check their return values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With