gpt4 book ai didi

c++ - 所有变量都根据它们在程序中声明的顺序连续存储吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:01:43 25 4
gpt4 key购买 nike

我正在学习数组以及当您尝试写入越界时它如何对您的程序有害。发现这一点后,我尝试越界读取。

我玩弄了一个 char 数组和一个 char 变量。

   //this occurs within int main()

char vowels[]{'a', 'e', 'i', 'o', 'u'};
char x = 'x';

std::cout << vowels[5]; //this outputs x

这让我想知道是否所有变量都按照声明的顺序连续存储。

最佳答案

来自标准(7.6.9.4):

The result of comparing unequal pointers to objects is defined in terms of a partial order consistent with the following rules:

  • If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript is required to compare greater.

  • If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member is required to compare greater provided the two members have the same access control ([class.access]), neither member is a subobject of zero size, and their class is not a union.

  • Otherwise, neither pointer is required to compare greater than the other.

由于前两个子句不适用于比较 x 的地址与 vowels 或其元素的地址,因此它们的地址没有意义可比性。

但在这种情况下,指针 vowels + 5(vowels[5] 尝试取消引用的地址)具有特殊含义。指向具有 n 元素的数组的索引 n 处的假设元素的任何指针都称为“结束指针之后的指针”。它代表数组末尾后的第一个字节。允许计算此地址但不能取消引用它。该标准有一条注释,明确指出您根本不能使用 vowels[5] (6.8.2.3):

[...] A pointer past the end of an object ([expr.add]) is not considered to point to an unrelated object of the object's type that might be located at that address. [...]

因此,即使 x 恰好位于 vowels + 5,您仍然不允许通过 vowels[5] 访问它。

关于c++ - 所有变量都根据它们在程序中声明的顺序连续存储吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58632775/

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