Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 605
bartop Avatar asked Oct 31 '25 21:10

bartop


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

like image 121
Vlad from Moscow Avatar answered Nov 03 '25 11:11

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!