Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer arithmetic disguised &(array[0])

Today I browsed some source code (it was an example file explaining the use of a software framework) and discovered a lot of code like this:

int* array = new int[10]; // or malloc, who cares. Please, no language wars. This is applicable to both languages
for ( int* ptr = &(array[0]); ptr <= &(array[9]); ptr++ )
{
   ...
}

So basically, they've done "take the address of the object that lies at address array + x".

Normally I would say, that this is plain stupidity, as writing array + 0or array + 9 directly does the same. I even would always rewrite such code to a size_t for loop, but that's a matter of style.

But the overuse of this got me thinking: Am I missing something blatantly obvious or something subtely hidden in the dark corners of the language?

For anyone wanting to take a look at the original source code, with all it's nasty gotos , mallocs and of course this pointer thing, feel free to look at it online.

like image 432
stefan Avatar asked Dec 27 '22 11:12

stefan


2 Answers

Yeah, there's no good reason for the first one. This is exactly the same thing:

int *ptr = array;

I agree on the second also, may as well just write:

ptr < (array + 10)

Of course you could also just make it a for loop from 0-9 and set the temp pointer to point to the beginning of the array.

for(int i = 0, *ptr = array; i < 10; ++i, ++ptr)
    /* ... */

That of course assumes that ptr is not being modified within the body of the loop.

like image 126
Ed S. Avatar answered Jan 08 '23 07:01

Ed S.


You're not missing anything, they do mean the same thing.

However, to try to shed some more light on this, I should say that I also write expressions like that from time to time, for added clarity.

I personally tend to think in terms of object-oriented programming, meaning that I prefer to refer to "the address of the nth element of the array", rather than "the nth offset from the beginning address of the array". Even though those two things are equivalent in C, when I'm writing the code, I have the former in mind - so I express that.

Perhaps that's the reasoning of the person who wrote this as well.

like image 42
Theodoros Chatzigiannakis Avatar answered Jan 08 '23 05:01

Theodoros Chatzigiannakis