What does output indicate when larger address is subtracted from smaller address in C/C++ programming?

被刻印的时光 ゝ 提交于 2020-07-22 05:50:09

问题


Given a snippet of code as:

int a[5];
printf("%u\n",&a[3]-&a[0]);
printf("%u",&a[0]-&a[3]);

now the output of first line in subtraction of addresses is as per formula ( (addg - adds)/size of data type ) where, addg is greater than adds. The output for above snippet in gcc is:

3
4294967293

The first line output (i.e. is 3) is obvious but what is the meaning of second output or what happens when larger address is subtracted from smaller one (i.e. adds - addg)?


回答1:


The problem in your code is that you have undefined behaviour. Not because of the pointer arithmetic but because you are printing signed integers using the %u format specifier. Change to the %td format (the t to specify a 'pointer difference' type) and you will see more meaningful results:

#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;
}

From this C11 Draft Standard (Section 6.5.6 Paragraph #9) (bolding mine):

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



来源:https://stackoverflow.com/questions/62991680/what-does-output-indicate-when-larger-address-is-subtracted-from-smaller-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!