加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中的负数组索引

发布时间:2020-12-16 10:46:06 所属栏目:百科 来源:网络整理
导读:在论坛中C中有关负数组的其他问题/答案,但我会要求32位编译器的答案: 如果我们有一个数组定义int test_array [5] = {1,2,3,4,5}; 那么后续陈述应该返回什么 test_array [20],test_array [-2],test_array [-32764],test_array [4294967700](大于32位可容纳的
在论坛中C中有关负数组的其他问题/答案,但我会要求32位编译器的答案:
如果我们有一个数组定义int test_array [5] = {1,2,3,4,5};

那么后续陈述应该返回什么
test_array [20],test_array [-2],test_array [-32764],test_array [4294967700](大于32位可容纳的值),*(a-32764)等

如果索引超出其声明的范围,编译器是否强制返回任何固定值?

解决方法

访问超出其边界的数组会导致未定义的行为(UB).
-ve索引不是有效索引,会导致未定义的行为.

一个未定义的Bheavior意味着任何事情都可以按字面意思发生,如果你很幸运你的程序会崩溃并且问题被检测到,如果你运气不好,代码一直运行良好,并且有一天所有地狱都会破裂.
因此,始终避免编写导致未定义行为的任??何代码.

Does the compiler force any fixed value to be returned in case index go beyond its declared range ?

没有
程序员必须处理这个问题.标准版不需要编译器为您提供任何指示/警告.标准只是将其定义为UB.

此外,该标准还标识了导致未定义行为的所有以下方案:

  • Addition or subtraction of a pointer into,or just beyond,an array object and an integer type produces a result that does not point into,the same array object.
  • Addition or subtraction of a pointer into,an array object and an integer type produces a result that points just beyond the array object and is used as the operand of a unary * operator that is evaluated.
  • An array subscript is out of range,even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读