Search code examples
c++cpointerspointer-arithmetic

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.


Solution

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