format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
时间: 2024-01-30 14:02:07 浏览: 56
这个错误是因为你使用了错误的格式化说明符。`%d` 是用于格式化整数的,但是你传递了一个指向整数的指针,导致编译器报错。
例如,下面的代码会产生这个错误:
```
int *p = malloc(sizeof(int));
scanf("%d", p); // 这里会产生上述错误
```
要解决这个问题,你需要使用 `%p` 格式化说明符,并将指针作为参数传递给 `printf` 函数,例如:
```
int *p = malloc(sizeof(int));
scanf("%d", p);
printf("The value of p is %p\n", (void *)p);
```
注意,在使用 `%p` 格式化说明符时,要将指针强制转换为 `void *` 类型。
相关问题
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
这个warning是因为你使用了%d来格式化一个long int类型的变量,而%d只能用来格式化int类型的变量。为了避免这个warning,你可以使用%ld来格式化long int类型的变量。例如:
```
long int num = 123456789;
printf("The number is: %ld\n", num);
```
这样就可以避免这个warning了。
format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]是什么报错,如何解决
这个报错是因为在使用scanf函数时,格式控制符中使用了%d,但是对应的参数却不是int类型的指针,而是int类型的变量。
解决这个报错的方法是,将scanf中对应%d的参数改为一个int类型的指针,例如:
```
int num;
scanf("%d", &num); // 将&num作为参数传递给scanf函数
```
这样就可以将num的地址作为参数传递给scanf函数,以便scanf函数将输入的值存储到num变量中。
另外,如果在编译时开启了-Wformat警告选项,就会出现这个报错。为了避免这个报错,可以在编译时加上-Wno-format选项来关闭格式化字符串的警告。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)