检查数组索引 [英] checking array indices

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

问题描述



当我定义

int R [99];

然后稍后用

x访问它= R [r]; C [x] = 7;

....

但x恰好是< 0或> 99,那么程序'有问题

变得不可预测。


有没有办法防止这种情况?

是否有程序或调试器或编译器哪个

在执行命令之前检查数组索引?

最终在索引超出范围时发出错误警告?


when I define
int R[99];
and then later access it with
x=R[r];C[x]=7;
....
but x happens to be <0 or >99 , then the program''s behavious
becomes unpredictable.

Is there a way to prevent this ?
Is there a program or debugger or compiler which
checks the array indices before executing the command and
eventually issues an error-warning when the index is out of range ?

推荐答案

Sterten写道:
Sterten wrote:
当我定义
int R [99];
然后用
x访问它= R [r]; C [x] = 7;
......
但x恰好是< 0或> 99,那么程序的行为就是


当然你的意思是但是x恰好是< 0或> 98"

变得无法预测。

有没有办法防止这种情况发生?
when I define
int R[99];
and then later access it with
x=R[r];C[x]=7;
...
but x happens to be <0 or >99 , then the program''s behavious
Surely you mean "but x happens to be <0 or >98"
becomes unpredictable.

Is there a way to prevent this ?




是的。不要编写错误的代码,试图超出

数组的界限。



Yes. Don''t write bad code that attempts to access beyond the bounds of
the array.




" ; Sterten" < ST ***** @ aol.com>在留言新闻中写道:20 *************************** @ mb-m05.aol.com ...

"Sterten" <st*****@aol.com> wrote in message news:20***************************@mb-m05.aol.com...

当我定义
int R [99];
然后用
x = R [r]; C [x] = 7;
...
但是x恰好是< 0或> 99,那么程序的行为就变得不可预测了。


你必须指x<上面的0或x> = 99.


你可以试试这个:


断言((无符号)i< 99) ;

t = R [i];

有没有办法防止这种情况?
是否有程序或调试器或编译器来检查执行命令前的数组索引,当索引超出范围时,最终会发出错误警告?

when I define
int R[99];
and then later access it with
x=R[r];C[x]=7;
...
but x happens to be <0 or >99 , then the program''s behavious
becomes unpredictable.
You must mean x < 0 or x >= 99 in the above.

You can try this:

assert((unsigned) i < 99);
t = R[i];

Is there a way to prevent this ?
Is there a program or debugger or compiler which
checks the array indices before executing the command and
eventually issues an error-warning when the index is out of range ?



>> int R [99];
>> int R[99];
然后用
x = R [r]; C [x] = 7;
and then later access it with
x=R[r];C[x]=7;

访问它

你的意思是x<上面的0或x> = 99.

你可以试试这个:

断言((无符号)i< 99);
t = R [i];



You must mean x < 0 or x >= 99 in the above.

You can try this:

assert((unsigned) i < 99);
t = R[i];




请记住assert()是一个调试工具。它有助于陷入不可能的b $ b或禁止的设计状态。但它不是为了捕获用户

级错误而设计的。


BTW,在许多开发系统上,断言()宏被忽略了
由于全球NDEBUG宏的定义,发布时



-

Emmanuel

C-FAQ: http://www.eskimo.com /~scs/C-faq/faq.html


C是一个敏锐的工具



Bare in mind that assert() is a debug tool. It helps to trap impossible
or forbidden by-design statuses. But it is not designed to trap user
level errors.

BTW, on many development systems, the assert() macro is simply ignored
at release time, due to the definition of the global NDEBUG macro.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html

"C is a sharp tool"

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

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