c++ - 不可分指针地址的减法

标签 c++ c pointers

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);

Ideone link .

我得到了输出 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/

相关文章:

c++ - 使用指针创建二维动态数组

c++ - 使用指针时的注意事项

c - 错误 : `TFD_NONBLOCK' undeclared (first use in this function)

c++ - char* str ="ab", str 和 &str 的混淆

c++ - 在定义可交换操作时减少代码重复

c++ - C++代码中的 “Undefined reference to operator<<”错误

c - del_elements()和search()函数无法正常工作

c++ - 二维函数最小化算法或 C/C++ 库

C - 未初始化的指针 -> 指向数组

c - 从链表中不兼容的指针类型赋值?