“'char *'出现问题,但参数的类型为'char(*)[1]'”

时间:2020-11-03 10:45:22

标签: c warnings

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);
    }

警告: 格式指定类型为'char ',但参数的类型为'char()[1]'[-Wformat] scanf(“%s”,&File_name); ~~~~ ^ ~~~~~~~~

箭头转到“&File_name”。

如何解决?谢谢。

1 个答案:

答案 0 :(得分:1)

scanf()期望char*中的%s

File_name的类型为char[1],因为它是一个元素数组,并且该元素已初始化为'\0'

表达式中的大多数数组都转换为指针,但例外之一是一元&的操作数(在这种情况下)。

因此,&File_name成为指向数组的指针,其类型为char(*)[1]

要解决此问题,请在&之前删除File_name。然后,数组File_name将转换为指向其第一个元素的char*

也:

  • 1个元素绝对太短而无法读取字符串。通过指定诸如char File_name[512] = "";之类的元素数量来分配更多元素。
  • '.txt'是一个多字符字符常量。它的值是实现定义的,将不是您想要的。您应该使用strstr(File_name,".txt")而不是strchr(File_name,'.txt')。 (strstr用于搜索字符串(包括中间),而不是用于检查后缀,但是它的行为比strchr()更好。)