当我运行这个时:
#include <stdio.h>
int main() {
int x = 1;
printf(x, "\n");
return 0;
}
它给了我这些错误:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x1)
Format string is not a string literal (potentially insecure)
Treat the string as an argument to avoid this
Incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *'
它输出:
(lldb)
但是,当我将其更改为:
printf("%s", x);
它工作得很好。 (输出“1”,如预期)
为什么需要转换字符(例如 %s、%d 等)?
最佳答案
它们需要告诉 printf
函数您要传递的参数的类型(和数量)。
该语言没有允许函数动态确定这一点的机制,因此格式字符串为它提供了解码它们的线索。
格式字符串始终是第一个参数,因为被调用的函数始终可以在同一位置访问它。像 printf 这样的函数通常仍然是用 C 编写的,因此只能使用该语言提供的那些函数。
关于c - 为什么需要转换字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749248/