C 错误 :format '%s' expects argument of type 'char *' but argument 2 has type 'char (*)[100]'

标签 c struct compiler-warnings c-strings strcpy

最近几天我正在做一个 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],其中索引从 0MAXSTRING-1

所以

scanf("%s",review)

是错误的,因为你必须传递一个 C 字符串到函数,然后你必须写:

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

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

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

第二次警告

对于struct bookRreview 成员也是一样。 所以

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

必须是

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

如您所见,您的 strcpy 调用中存在第二个问题:第二个参数解决了超出范围的字符串数组,即调用 Undefined Behavior。 .

其他警告

您的代码中有更多警告:

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

最后的考虑

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

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

关于C 错误 :format '%s' expects argument of type 'char *' but argument 2 has type 'char (*)[100]' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37291409/

相关文章:

c - 如何在 C 中创建一个数组来容纳 2 种相似类型的结构?

c - printf(s) 和 printf ("%s", s) 之间的根本区别是什么?

Python CFFI - 无法在函数调用中使用格式化的 Python 字符串作为字节数组

c - boolean 函数错误

调用函数指针(语法)

c++ - C++中指针结构的运算符重载

c++ - 宏的实际参数太多?

c# - Visual Studio 警告级别的含义?

c - 赋值涉及二元运算时,编译器如何处理自动变量

c - strtok 删除除第一个标记之外的字符串