Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

pointer arithmetic - Access element beyond the end of an array in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Thus, this is OK:

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

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

(Doing *end would be an error.)

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...