为什么此代码给出警告:格式'%s'期望类型为'char *',而参数2为类型'char(*)[11]'? [英] Why does this code give warning: format '%s' expects type 'char *' but argument 2 has type 'char(*)[11]'?

查看:99
本文介绍了为什么此代码给出警告:格式'%s'期望类型为'char *',而参数2为类型'char(*)[11]'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <stdlib.h>
#define RIG 5
#define COL 11

int main()
{
    FILE *fp;
    fp=fopen("swamp.txt","r");
    if((fp=fopen("swamp.txt","r"))==NULL)
    {
        puts("ERROR!");
        return -1;
    }
    char *swamp[RIG][COL];
    while(fscanf(fp,"%s",swamp)!=EOF)
    {
        printf("%s\n",swamp);
    }

    fclose(fp);

    return 0;
}

我正在处理文件,并且在while内收到fscanf的2条警告.有人可以向我解释为什么吗?

I'm working with files and I'm getting 2 warnings for the fscanf inside the while. Can somebody explain to me why?

推荐答案

假设swamp.txt包含:

marsh
bog
quagmire
morass
fen

,并且您要将这些行读入程序中的数组swamp.然后,您可以按照以下方式修改代码.请注意,这避免了两次打开文件,以及其他清除操作.

and that you want to read these lines into the array swamp in your program. Then you might revise your code along these lines. Notice that this avoids opening the file twice, amongst other cleanup operations.

#include <stdio.h>

#define RIG 5
#define COL 11

int main(void)
{
    const char filename[] = "swamp.txt";
    FILE *fp = fopen(filename, "r");
    if (fp == NULL)
    {
        fprintf(stderr, "failed to open file '%s' for reading\n", filename);
        return -1;
    }
    char swamp[RIG][COL];
    int i = 0;
    while (i < RIG && fscanf(fp, "%10s", swamp[i]) == 1)
        i++;

    fclose(fp);

    for (int j = 0; j < i; j++)
        printf("%d: %s\n", j, swamp[j]);

    return 0;
}

输出为:

0: marsh
1: bog
2: quagmire
3: morass
4: fen

请注意,该代码通过对读取的单词进行计数来防止长文件溢出.您已经检查了fopen()-很好.但是,我改进了错误消息.我认为,永远不要使用文字字符串来调用fopen()作为文件名,因为当您在打开文件时报告错误时,您需要在错误消息中输入文件名,因此您必须重复自己的操作.我固定了数组的类型,因此它是char的2D数组,而不是(未初始化的)char指针的2D数组.我安排将数组的每一行依次传递给fscanf().我也限制了每个单词的输入长度,以防止在那里出现溢出.

Note that the code protects against overflow from a long file by counting words as they're read. You already checked fopen() — that was good. I improved the error message, though. In my opinion, you should never call fopen() with a literal string for the file name because when you report an error on opening the file, you need the file name in the error message, so you'd have to repeat yourself. I fixed the type of the array so it is a 2D array of char and not a 2D array of (uninitialized) char pointers. I arranged to pass each row of the array to fscanf() in turn. I limited the length of the input for each word to prevent overflows there, too.

这篇关于为什么此代码给出警告:格式'%s'期望类型为'char *',而参数2为类型'char(*)[11]'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆