c - 当我在 printf() 中的字符串后添加一个带加号的 int 时会发生什么

标签 c printf

我在一个混淆的程序中阅读了如下代码。

我想知道为什么编译器在我这样做时给我警告而不是错误。代码真正想做什么以及为什么编译器建议我使用数组?

#include <stdio.h>
int main()
{
    int f = 1;
    printf("hello"+!f);
    return 0;
}

warning: adding 'int' to a string does not append to the string [-Wstring-plus-int]
printf("hello"+!f);
       ~~~~~~~^~~
note: use array indexing to silence this warning
printf("hello"+!f);
              ^
       &      [  ]

最佳答案

考虑语句 printf("hello");

此语句将字符串文字 "hello" 发送到 printf(); 函数。


现在让我们分别考虑代码

char* a = "hello";

这将指向存储字符串文字 "hello" 的地址。

如果有人这样做会怎样

char* a = "hello" + 1;

它将使a 指向存储"ello" 的地址。 "hello"+ 1的地址,指向字符串字面量"ello"

的地址

将此应用于您的代码

printf("hello"+!f);

f 的值为 1!f 的值为 0。所以,最终它会指向字符串文字"hello"+ 0的地址,也就是"hello"。然后将其传递给 printf()


您没有收到错误,因为它不是错误。

关于c - 当我在 printf() 中的字符串后添加一个带加号的 int 时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707276/

相关文章:

c - 为什么我们需要在 C++ printf 函数中的格式说明符中指定类型?

c++ - 保护多线程访问的类实例

c - 通过 UDP 发送时丢失数据

C:下标值既不是数组也不是指针

c++ - 在 C/C++ 中释放/删除 union malloc/new Array

c - STM32 printf() 重定向

c - select() 无法正常工作,错误在哪里?

C : printf() not thread safe with flockfile()

C - printf 输出说明 ("%d %d\n",k=1,k=3);

c - 将 printf 重定向到串行端口