使用(+ ve整数)+“一些字符串"在printf中? [英] Using (+ve integer) + "some string " in printf?

查看:66
本文介绍了使用(+ ve整数)+“一些字符串"在printf中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

void main() {
    printf(2 + "abcdefgh");
}

此代码如何打印 cdefgh ?如果我使用 2- 2 * 或任何其他运算符,则编译器将引发错误.

How does this code print cdefgh? Compiler throws an error if I use 2- or 2* or any other operator.

推荐答案

使用诸如"abcdefgh" 之类的字符串文字时,实际上您有一个指向该字符串所在的内存区域的指针.基本上,您将指向该位置的指针传递给 printf ,并指示其将指针向前移动2个位置,从而导致从第3个字符开始的字符串而不是第一个字符

When using string literals such as "abcdefgh" you actually have a pointer to a section on memory where this string resides. Basically you pass to printf a pointer to that location and instructs it to move the pointer 2 locations ahead, resulting in the a string starting from the 3rd char instead of the first

请注意,您可以使用-,但是您需要像使用指针算术一样使用它,例如

Note that you can use - but you need to use it like you do pointers arithmetic, like

printf("abcdefgh"-0);//使用-N,其中N> 0为UB

因此,此代码有效

int main()
{
    printf("abc\n" - 0);
    printf(1+"def");
    return 0;
}

,但是使用 *,/不会(同样,按位运算符 |,& 无效)

but using *,/ will not (also bitwise operators |,& will not be valid)

这篇关于使用(+ ve整数)+“一些字符串"在printf中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆