gpt4 book ai didi

c++ - 代码的有效性

转载 作者:IT老高 更新时间:2023-10-28 22:34:42 26 4
gpt4 key购买 nike

考虑以下代码:

void populate(int *arr)
{
for(int j=0;j<4;++j)
arr[j]=0;
}

int main()
{
int array[2][2];
populate(&array[0][0]);
}

在本地社区对此代码是否有效进行了讨论(我应该提及它的名称吗?)。有人说它调用了 UB,因为它违反了

C++ 标准($5.7/5 [expr.add])

"If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined."

但我看不出代码有什么问题,代码对我来说完全没问题。

所以,我只想知道这段代码是否有效?我错过了什么吗?

最佳答案

您的 arrayint[2] 的两个数组,而您的函数 populate() 将其视为 的单个数组>int[4]。根据编译器决定对齐 array 元素的确切方式,这可能不是一个有效的假设。

具体来说,当 j 为 2 并且您尝试访问 arr[2] 时,这超出了 mainarray[0] 因此无效。

关于c++ - 代码的有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036104/

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