gpt4 book ai didi

c++ - 在C/C++编程中,从较小的地址减去较大的地址时,输出指示什么?

转载 作者:行者123 更新时间:2023-12-01 15:10:24 25 4
gpt4 key购买 nike

给出一小段代码为:

int a[5];
printf("%u\n",&a[3]-&a[0]);
printf("%u",&a[0]-&a[3]);
现在,地址减法的第一行输出按公式计算((addg-增加)/数据类型的大小),其中,addg大于adds。
在gcc中上述代码段的输出为:
3
4294967293
第一行输出(即3)是显而易见的,但是第二输出的含义是什么?或者从较小的地址减去较大的地址(即加-addg)时会发生什么?

最佳答案

代码中的问题是您的行为不确定。不是因为指针运算,而是因为您正在使用%u格式说明符打印带符号整数。更改为%td格式(使用t指定“指针差异”类型),您将看到更有意义的结果:

#include <stdio.h>
#include <stddef.h>

int main()
{
int a[5];
printf("%td\n", &a[3] - &a[0]); // Shows "3"
printf("%td", &a[0] - &a[3]); // Shows "-3"
return 0;
}
从这个 C11 Draft Standard(第 部分6.5.6 第9段)中(粗体显示):

When two pointers are subtracted, both shall point to elements of thesame array object, or one past the last element of the array object;the result is the difference of the subscripts of the two arrayelements. The size of the result is implementation-defined, and itstype (a signed integer type) is ptrdiff_t defined in the <stddef.h>header ...

关于c++ - 在C/C++编程中,从较小的地址减去较大的地址时,输出指示什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62991680/

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