用C负数组索引 [英] Negative array index in C

查看:134
本文介绍了用C负数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有已经在论坛上用C负面阵列上的其他问题/答案,但我会要求回答这些为32位编译器:
如果我们有一个数组定义 INT test_array [5] = {1,2,3,4,5};

There have been other question/answers on negative array in C in the forum, but i would request the answer to these for a 32-bit compiler : If we have an array defined int test_array[5] = {1,2,3,4,5};

那应该以下语句返回
test_array [20] test_array [-2] test_array [-32764] test_array [4294967700] (数值大于什么32位可容纳), *(A-32764)

then what should following statements return test_array[20], test_array[-2], test_array[-32764], test_array[4294967700](value greater than what 32 bit can accommodate), *(a-32764) etc

该编译器力的情况下,指数要返回任何固定值超出其宣称的范围是多少?

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

推荐答案

访问超越其边界结果的数组中的未定义行为(UB)。结果
一个 -ve 指数是不是在未定义行为的有效指标和结果。

Accessing an array beyond its bounds results in Undefined Behavior(UB).
An -ve index is not an valid index and results in Undefined Behavior.

这是未定义Bheavior意味着什么可以从字面上发生,如果你是幸运的你的程序将崩溃,这个问题被检测到,如果你是一个倒霉的code正常工作一直和所有的地狱破散的一天。结果
所以,总是避免写任何code,这会导致未定义Behaivor

An Undefined Bheavior means anything can happen literally, If you are lucky your program will crash and the problem gets detected, If you are unlucky the code works fine all along and all hell breaks loose some day.
So, always avoid writing any code which causes an Undefined Behaivor.

该编译器力的情况下,指数要返回任何固定值超出其宣称的范围是多少?

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

NO 结果
程序员必须照顾这。该标准并不需要编译器给你任何指示/对这一信息。标准警告只是将它定义为一个 UB

此外,该标准确定所有在以下情况下会导致未定义行为:

Furthermore the standard identifies all of the following scenarios to cause Undefined Behavior:


      
  • 添加或指针到,或者只是超出了减法,数组对象和整数类型产生不点进去,或者只是超越,相同的数组对象的结果。

  •   指针指向,或者只是超出
  • 加法或减法,数组对象和整数类型产生一个指向刚刚超越数组对象,并用作目*运算符的运算结果被评估。

  •   
  • 数组下标超出范围,即使对象是与给定的下标显然是可访问的(如在左值前pression A [1] [7] 给出的声明 int类型的[4] [5] )。

  •   
  • 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, or just beyond, the same array object.
  • Addition or subtraction of a pointer into, or just beyond, 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]).

这篇关于用C负数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆