C 中是否定义了不可分指针地址的减法?在 C++ 中?
这是一个例子:
void* p = malloc(64);
int* one = (int*)((char*)p);
int* two = (int*)((char*)p + 7);
printf("%x %x %d %d\n", one, two, sizeof(int), two - one);
我得到了输出 8a94008 8a9400f 4 1
,所以它似乎进行了除法并截断了余数。行为是否已定义?
最佳答案
根据 5.7.6,这是未定义的行为:
When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. [...] Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.
在您的代码中,指针 two
没有指向与指针 one
相同的 int
数组的元素。事实上,它并没有指向 p
的任何数组元素,因为它指向其中一个元素的“中间”(这本身就是一种未定义的行为)。
关于c++ - 不可分指针地址的减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36030781/