在C语言中,只要不取消引用,就可以创建一个指向数组最后一个元素后一个元素的指针,并在指针算术中使用它:
int a[5], *p = a+5, diff = p-a; // Well-defined
然而,以下是瑞银:
p = a+6;
int b = *(a+5), diff = p-a; // Dereferencing and pointer arithmetic
现在我有一个问题:这是否适用于动态分配的内存?假设我在指针算术中只使用了一个指向最后一位的指针,而没有取消对它的引用,malloc()
成功了.
int *a = malloc(5 * sizeof(*a));
assert(a != NULL, "Memory allocation failed");
// Question:
int *p = a+5;
int diff = p-a; // Use in pointer arithmetic?