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

标签 c printf pointer-arithmetic format-specifiers

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/

相关文章:

c - 我正在尝试以小端方式从结构内的值读取所有 64 位

php - 使用/发送 POST 数据时的 libcurl C 问题(不是 C++)

c - 查找有序数组的众数

c - 为什么在更改 main 的签名时会出现段错误?

c++ - 为什么带后缀运算符的解引用指针用括号表示,仍然可以得到之前解引用的值?

c - 用字符串做数学?

C - 如何从数组中提取偶数并将它们放入另一个名为 EvenNumbers 的数组中?

C char数组不是字符串模式?

c - 用 0 填充字符串的 printf

perl - 为什么 Perl 与 sprintf 舍入不一致?