gpt4 book ai didi

c - 指针增量与整数增量不同?

转载 作者:行者123 更新时间:2023-11-30 18:37:46 25 4
gpt4 key购买 nike

我编写了这段代码并观察到了一个有趣的行为,如果有人可以评论为什么会发生这种情况,那就太好了!

int main()
{
char *name = "ABCDEF";
int i = 0;

printf("\n Base address of name %u", name);
printf("\n Address ++name %u", ++name);
printf("\n Address name + 1 %u", name + 1);
printf("\n Adddress name +2 %u", name + 2);
printf("\n Base address of name %u", name);

printf("\n i %d", i);
printf("\n i+1 %d", i + 1);
printf("\n i+2 %d", i + 2);
printf("\n i+3 %d", i + 3);
printf("\n i %d", i);

return 0;
}

最后一行应该返回未发生的原始指针值,这也与整数变量不同,在整数变量中,加法是在原始值 0 的情况下发生的,对于指针来说,它是从前一个值发生的。

enter image description here

最佳答案

关于 N1570 中的前缀增量运算符(重点是我的):

6.5.3.1 Prefix increment and decrement operators

Semantics

2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1).

name变成name + 1之后printf("\n Address ++name %u", ++name);被执行,给你 4210689在最后一行。

<小时/>

顺便说一句,要打印指向对象的指针的值,即该对象的地址,您应该使用 printf("\n Address ++name %p", (void *)++name);相反(但是,指向函数的指针被排除在外)。

关于c - 指针增量与整数增量不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35910944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com