Search code examples
cwarnings

Problem with " 'char *' but the argument has type 'char (*)[1]'"


FILE *fd;
char File_name[]="";
<...>
printf("Enter the name of the file where you want the results to be saved. \n");
    printf("DON'T FORGET that file must end with .exe \n");
    scanf("%s",&File_name);
    while(strchr(File_name,'.txt')==NULL)
    {
        printf("The end of the file name is not correct. Please try again. \n");
        printf("File name: ");
        scanf("%s",&File_name);
    }

Warning: format specifies type 'char ' but the argument has type 'char ()[1]' [-Wformat] scanf("%s",&File_name); ~~~~^~~~~~~~~~

Arrow goes to "&File_name".

How to fix it? Thank you.


Solution

  • scanf() expects char* for %s.

    File_name has type char[1] because it is one-element array and the element is initialized to '\0'.

    Most arrays in expressions are converted to a pointer, but one of the exception is an operand of unary & (this case).

    Therefore, &File_name becomes a pointer to the array and its type is char(*)[1].

    To fix, remove the &s before File_name. Then the array File_name will be converted to char* pointing at its first element.

    Also:

    • 1 element is definitely too short to read strings. Allocate more elements by specifying number of elements like char File_name[512] = "";.
    • '.txt' is a multi-character character constant. Its value is implementation-defined and will not be what you want. You should use strstr(File_name,".txt") instead of strchr(File_name,'.txt'). (strstr is for searching for strings (including middle), not for checking suffix, but it will behave better than strchr()).