1

我有这个 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]
4

2 回答 2

1

1传入char数组scanf()的地址,而不是 a 的地址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);        
于 2013-09-15T02:44:35.003 回答
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;
}

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

于 2013-09-14T03:25:48.240 回答