【问题标题】:format '%s' expects argument of type 'char *', but argument 2 has type 'char **'格式“%s”需要“char *”类型的参数,但参数 2 的类型为“char **”
【发布时间】:2013-09-14 03:18:10
【问题描述】:

我有这个 C 代码:

#include <stdio.h>
#include <stdlib.h>
int main(){
    char *bitstr;

    printf("Enter a bitstring or q for quit: ");
    scanf("%s", &bitstr);
    return 0;
}

我不断收到以下错误。我究竟做错了什么?

warning: format '%s' expects argument of type 'char *', but 
argument 2 has type 'char **' [-Wformat]

【问题讨论】:

标签: c warnings


【解决方案1】:

试试这个:

#include <stdio.h>
#include <stdlib.h>

#define MAX 100

int main(){
    char bitstr[MAX] = "";

    printf("Enter a bitstring or q for quit: ");
    scanf("%s", &bitstr);

    // or fgets(bitstr);

    return 0;
}

尝试定义或分配字符串/字符数组的大小。

【讨论】:

  • #define 100 MAX 应该是#define MAX 100,并建议fgets(); 而不是gets(bitstr);scanf("%s", &amp;bitstr);
  • 不。 &amp;bitstrchar (*)[100] 类型; %s 需要 char* 类型的参数。删除&amp;scanf("%s", bitstr)bitstr 是数组类型,它衰减为指向数组第一个元素的指针。重要提示:scanf("%s", ...)gets() 本质上都是不安全的,以至于 gets 已从语言中删除。他们无法防止输入过长。
【解决方案2】:

1 传递地址scanf() 中的char 数组,而不是char* 的地址。
2 确保不会覆盖目标缓冲区。
3 调整缓冲区大小。从其他帖子中可以明显看出,您需要int 的二进制文本表示。假设您的 int 是 8 个字节(64 位)。

#include <stdio.h>
#include <stdlib.h>
int main(){
    char bitstr[8*8 + 1];  // size to a bit representation of a big integer.
    printf("Enter a bitstring or q for quit: ");
    //Change format and pass bitscr, this results in the address of bitscr array.
    scanf("%64s", bitstr);
    return 0;
}

我更喜欢 fgets() 和 sscanf() 方法。

char buf[100];  // You can re-use this buffer for other inputs.
if (fgets(buf, sizeof(buf), stdin) == NULL) { ; /*handle error or EOF */ }
sscanf(buf, "%64s", bitstr);        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多