C 错误:格式“%s”需要“char *”类型的参数,但参数 2 的类型为“char (*)[100]”

2024-04-29

过去几天我正在用 c 进行练习,并且收到此警告(如标题所示)。我已经尝试了很多东西,但我真的不知道如何准确地解决这个问题。我不擅长编程,所以会有错误。以下是我正在使用的结构(无法更改,因为它们就是这样给出的):

    typedef struct bookR* book;
struct bookR{
    char author[MAXSTRING];
    enum genres{fiction,scientific,politics};
    int id;
    char review[MAXLINES][MAXSTRING];

};

typedef struct nodeR* node;
struct nodeR{
    book b;
    node next;

};

typedef struct listR* list;
struct listR{
    node head, tail; 
    int size;
};

这是出现问题的部分代码:

 void addBook(book b, list bList){
char author [MAXSTRING];
int id;
char review [MAXSTRING][MAXLINES];
printf ("Give the author,`enter code here` id and review of the new book respectively");
scanf("%s",author);
scanf("%d",&id);
scanf("%s",review);
node k=(node)malloc(sizeof(struct nodeR));
assert(k);
k->next=NULL;
strcpy(k->b->author,author);
k->b->id=id;
strcpy(k->b->review,review[MAXSTRING]);}

这是我收到的警告:

  warning: format '%s' expects argument of type 'char *' but argument 2 has type 'char (*)[100]' [-Wformat=]
scanf("%s",review);
warining:passing argument 1 of 'strcpy' from incompatible pointer tupe [-Wincompatible-pointer-types]
strcpy(k->b->review,review[MAXSTRING]);

任何帮助深表感谢。感谢您抽出时间,对这么长的帖子表示歉意。


第一次警告

char review [MAXSTRING][MAXLINES];

它是一个矩阵,在您的情况下可以看作是 C 字符串数组。

每个 C 字符串是review[index]索引从哪里来0 to MAXSTRING-1

So

scanf("%s",review)

是错误的,因为您必须将单个 C 字符串传递给函数,那么您必须编写:

scanf("%s",review[index]);

我建议您将输入字符串限制为每个字符串允许的最大字符数MAXLINES-1使用,而不是scanf:

fgets(review[index], MAXLINES, stdin);

第二次警告

同样的事情review成员struct bookR. So

strcpy(k->b->review,review[MAXSTRING]);

must be

strcpy(k->b->review[index],review[MAXSTRING-1]);

正如您所看到的,您的 strcpy 调用存在第二个问题:第二个参数地址超出范围的字符串数组,调用未定义的行为 https://en.wikipedia.org/wiki/Undefined_behavior.

其他警告

您的代码中有更多警告:

test.c:666:45: warning: declaration does not declare anything
     enum genres{fiction,scientific,politics};
                                             ^

最后的考虑因素

我猜你想将定义切换到矩阵定义中,就像你所做的那样struct bookR, like:

char review [MAXLINES][MAXSTRING];

我认为最好的选择是要求每个数据都具有特定的prinf这是scanf/fgets.

printf ("Give the author: ");
fgets(author, MAXSTRING, stdin);
printf ("Enter id: ");
scanf("%d",&id);
printf ("Enter review of the new book respectively: ");
fgets(review[index], MAXSTRING, stdin);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C 错误:格式“%s”需要“char *”类型的参数,但参数 2 的类型为“char (*)[100]” 的相关文章

随机推荐