Search code examples
carraysfgets

Passing argument 3 of “fgets ” from incompatible pointer type


I have a warning on my program and I don't know how to solve this. First I have the warning passing argument 3 of "fgets" from incompatible pointer type. Here is my program:

bool get_name(char name[],char buff[])
{

    if(isalpha(buff))
    {
    fgets(name,sizeof(MAXNAME),buff);
    return name;
    }
    else
    {
            return false;
    }
}

Solution

  • Given the task description:

    • copy a string starting with an alphabetic character and continuing with alphanumeric characters from buff to name

    the code should not be using fgets() at all. (See the comments to the question for discussion of what would be necessary if fgets() was relevant.) The code should be something like:

    bool get_name(char name[], char buff[])
    {
        if (isalpha(buff[0]))
        {
            int i;
            for (i = 0; isalnum(buff[i]); i++)
                name[i] = buff[i];
            name[i] = '\0';
            return true;
        }
        else
        {
            name[0] = '\0';
            return false;
        }
    }
    

    This code assumes that name is big enough to hold any identifier that is in buff. Note that the isalnum(buff[i]) test will pass when i is 0, but the value checked will always be alphabetic because of the outer test.

    Example program

    #include <ctype.h>
    #include <stdbool.h>
    
    extern bool get_name(char name[], char buff[]);
    
    bool get_name(char name[], char buff[])
    {
        if (isalpha(buff[0]))
        {
            int i;
            for (i = 0; isalnum(buff[i]); i++)
                name[i] = buff[i];
            name[i] = '\0';
            return true;
        }
        else
        {
            name[0] = '\0';
            return false;
        }
    }
    
    #include <assert.h>
    #include <stdio.h>
    
    static void test(char *buffer)
    {
        char name[64];
    
        if (get_name(name, buffer))
            printf("Got name [%s] from [%s]\n", name, buffer);
        else
        {
            printf("No name in [%s]\n", buffer);
            assert(name[0] == '\0');
        }
    }
    
    int main(void)
    {
        char buffer1[] = "Adelson23 and all that!";
        char buffer2[] = "=not an identifier=";
    
        test(buffer1);
        test(buffer2);
        return 0;
    }
    

    Example output

    Got name [Adelson23] from [Adelson23 and all that!]
    No name in [=not an identifier=]