In the book C Primer Plus, Fifth Edition, in Chapter 10. Arrays and Pointers:

C guarantees that, given an array, a pointer to any array element, or to the position after the last element, is a valid pointer. But the effect of incrementing or decrementing a pointer beyond these limits is undefined. Also, you can dereference a pointer to any array element. However, even though a pointer to one past the end element is valid, it's not guaranteed that such a one-past-the-end pointer can be dereferenced.

I confused why a valid pointer might not be dereferenced,
and what the one-past-the-end pointer is used for?

Recommended Answers

All 8 Replies

I confused why a valid pointer might not be dereferenced

It's a valid pointer alone, not a valid array element. This gives compilers the freedom to always implement one past the end as a single byte (the smallest addressable unit) and not waste space creating a full unused element of the array type.

what the one-past-the-end pointer is used for?

It simplifies iteration and size calculations.

Thaks a lot!

Can you give me a code example to show me the use of the one-past-the-end pointer?

One use is iterators. The idea is that you have a begin iterator that points to the first valid element in the sequence and an end iterator that points to one past the final element in the sequence. Increment the begin iterator until it's equal to the end iterator (a common pattern in C++) and process the contents:

#include <stdio.h>

int main(void)
{
    char a[14] = "this is a test";
    char *begin = a;
    char *end = a + 14;

    // Iteration style using begin/end
    while (begin != end)
        printf("%c\n", *begin++);

    return 0;
}

Sorry, I still not really understand.

How about following code for the pointer that points to TWO past the final element in the array. Can I say the pointer char *end = a + 15 is a valid pointer? It does not points to a value but it points to the second opsition after the final element in the array?

#include <stdio.h> 
int main(void)
{    
char a[14] = "this is a test";    
char *begin = a;    
char *end = a + 15;  
while (begin != end)        
printf("%c\n", *begin++);     
return 0;}

Sorry, I meant position.

Can I say the pointer char *end = a + 15 is a valid pointer?

No. The C standard states that pointer arithmetic must result in a pointer to a valid element or one past the end of the array. Any further either before the first element or beyond one past the end is undefined. You don't even have to dereference that pointer; simply calculating it invokes undefined behavior.

Thank you again for your help!

hey nice thread
cleared the concept of valid pointer in C.
some thing new to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.