Search code examples
cfor-looppointer-arithmetic

Pointer one-past-variable


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
}

Solution

  • 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.