Warning: return from incompatible pointer type in C

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.

Leave a Comment