gpt4 book ai didi

c - 为什么在使用 printf 时在地址上使用表达式会表现得很奇怪

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

typedef struct nodes {
int da;
struct nodes *ptr;
} node;

node init;

printf("%d %d %d\n", &init, &init-2 ,6295648-2);

打印

6295648 6295616 6295646

为什么从地址中减去 2 会减去 32(因此从地址中减去 1 会减去 16)?

最佳答案

首先,要打印地址,您应该使用 %p格式说明符并将参数转换为 (void *) ,按照 printf() 的要求。否则,对提供的格式说明符使用错误类型的参数会调用 undefined behavior .

也就是说,关于指针算术,引用 C11 ,第 §6.5.6 章

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. [...]

这意味着,指针算术遵循指针的数据类型。整数与指针相加(或相减)的结果不仅仅是另一个数字,它是另一个(可能的)元素(只要存在)的地址。

In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. [...]

关于c - 为什么在使用 printf 时在地址上使用表达式会表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38950887/

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