c - 为什么需要转换字符?

标签 c printf

当我运行这个时:

#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/

相关文章:

c - SIMD signed with unsigned multiplication for 64-bit * 64-bit to 128-bit

c - 函数指针

c - 在 linux 下,c 函数有疯狂的行为

C printf 在输出的中间放置一个制表符

C - printf() 是否会导致线程休眠?

c - 了解对象表示

c - 为什么 Fread 以相反的顺序读取 unsigned-int?

PHP 打印; Css 仅适用于数据库的第一行

c - 奇怪的 printf 输出

bash - 在 bash 中重用字符串