c - 为什么在 C 中,像下面代码中提到的警告行会采用下一行的字符串并打印?

标签 c printf

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello world!\n");
    printf("a"+14);

    printf("tera kya hoga kalia \n\n");

    return 0;
}

//此代码打印

世界你好!

卡利亚

寺伽霍加卡利亚

//为什么要获取下一行的打印数据。

//是的,C 语言新手!!!

最佳答案

行:

printf("a"+14);

相当于:

char const* s1 = "a";
char const* s2 = s1 + 14;
printf(s2);

表达式s1 + 14计算结果为无效指针。给定 s1 的值,仅 s1+0s1+1是有效的指针。

s2是一个无效的指针,该行

printf(s2);

是未定义行为的原因。

事实上,给定 s1 的值,只是计算s1+i对于所有人来说都是未定义的行为i < 0i > 2 .

来自 EOF 的评论:

6.5.6 Additive operators 8 [...] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

关于c - 为什么在 C 中,像下面代码中提到的警告行会采用下一行的字符串并打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36346772/

相关文章:

c++ - 使用 libclang/libtooling

检查 double 的条件是一个整数不起作用

c - 用C语言解析数据格式

c++ - printf() 混淆 - 尝试打印字符串时打印 (null) 并在打印缓冲区时打印正确的值

c++ - 为什么此代码使用带字符串的映射 (C++) 会出现运行时错误?

c - printf 语句未在 netbean 中的 scanf 语句之前执行

c - 在 C 中查找函数的大小

在 C 中导致 gets() 在 SIGINT 时退出

c - 如何根据从文件读取的字符确定数组的大小?

c - 如何避免同一输出出现多个印记