Ç - 元素超出数组的末尾 [英] C - element beyond the end of an array

查看:115
本文介绍了Ç - 元素超出数组的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读K&安培;的r书C,并发现C,它指针运算允许访问一个元素超出数组的结尾。我知道C允许做几乎任何记忆,但是我就是不明白,这是什么特点的目的是什么?

I've been reading K & R's book on C, and found that pointer arithmetic in C allows access to one element beyond the end of an array. I know C allows to do almost anything with memory but I just don't understand, what is the purpose of this peculiarity?

推荐答案

C不容许的访问以存储超过数组的结尾。它,然而,允许一个指针在一个元件指向超出数组的末尾。这种区别是很重要的。

C doesn't allow access to memory beyond the end of the array. It does, however, allow a pointer to point at one element beyond the end of the array. The distinction is important.

因此​​,这是确定:

char array[N];
char *p;
char *end;

for (p = array, end = array + N; p < end; ++p)
    do_something(p);

(否则 *结束将是一个错误。)

这说明了为什么这个功能非常有用的原因:在(不存在)元素的指针指向后数组的结尾是比较,如在循环中非常有用

And that shows the reason why this feature is useful: a pointer pointing at the (non-existent) element after the end of the array is useful for comparisons, such as in loops.

从技术上讲,这是一切的C标准允许的范围。然而,在实践中,C实现(编译器和运行时)不检查是否存取存储器超出阵列的末端,无论是一个元件或多个。那里将必须边界检查,这会减慢程序的执行。该种方案C是最适合(系统编程,通用库)往往比从安全和安全边界检查将给予更多的速度中获益。

Technically speaking, that is everything the C standard allows. However, in practice, the C implementation (compiler and runtime) does not check whether you access memory beyond the end of the array, whether it is one element or more. There would have to be bounds checking and that would slow down program execution. The kinds of programs C is best suited for (systems programming, general purpose libraries) tend to benefit more from the speed than the security and safety bounds checking would give.

这意味着C是也许不是通用的应用程序编程的好工具。

That means C is perhaps not a good tool for general purpose application programming.

这篇关于Ç - 元素超出数组的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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