Pointer one-past-variable

Viewed 81

From what I know it is perfectly legal in C to check if pointer is one element past the end of an array like this:

char arr[16];

for (char* ptr = arr; ptr != arr + (sizeof arr / sizeof arr[0]); ++ptr) {
   // some code
}

My question is if it is well defined and legal to do something like this (note that this code is just an example to show my point. In real code I have functions handling arrays and I wonder if I can pass just pointer to local char variable and size 1):

char c;
for (char* ptr = &c; ptr != (&c + 1); ++ptr) {
   // some code
}
2 Answers

From the C Standard (6.5.6 Additive operators)

7 For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

So this loop

for (char* ptr = &c; ptr != (&c + 1); ++ptr) {
   // some code
}

is correct.

The main reason for the rule is that it allows "iterator-like" access (think C++ iterator if that's familiar). This is valid and well-defined:

char arr[16];
const char* begin = arr;
const char* end   = &arr[16];

for(char* ptr=begin; ptr!=end; ptr++)

However, we are not allowed to de-reference arr[16], just point at it.

Related