gpt4 book ai didi

arrays - 连续数组

转载 作者:行者123 更新时间:2023-12-04 11:09:41 25 4
gpt4 key购买 nike

我很好奇C18标准中的一句话:

Two pointers compare equal if and only if both are null pointers, bothare pointers to the same object (including a pointer to an object anda subobject at its beginning) or function, both are pointers to onepast the last element of the same array object, or one is a pointer toone past the end of one array object and the other is a pointer to thestart of a different array object that happens to immediatelyfollow the first array object in the address space. § 6.5.9 6


为什么数组后面的对象必须是另一个数组?不能简单地成为与数组基类型相同类型的对象(例如 int 紧跟在 int[] 之后)?
难怪我试过这个代码:
#include <stdio.h>

struct test { int arr[10]; int i; };

int main() {
struct test t;
int *p, *q;
p = t.arr + 10;
q = &t.i;
if (p == q)
printf("Equal pointers.");
return 0;
}
它产生相等的指针。这种行为是否根本没有保证,只是实现定义的巧合?

最佳答案

OP: Why the object following the array has to be necessarily another array?


它不是。 “...开始不同的数组...”是一种简化。下一个规范是:

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type. C17dr § 6.5.9 7



OP: Couldn't simply be an object which type was the same as the array base type (like an int immediately following an int[])?


是的。

关于arrays - 连续数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63594716/

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