-1

A project I did last year involved pointer arithmetic. When I did that, I was able to treat pointers like memory addresses and add or subtract from them as I wanted. For example, if int* p == array[0], then you'd know that p + sizeof(int) would find array[1]. That doesn't seem to be the case anymore, as I have a relatively well-known interview question in front of me in which I have to debug the following code:

void 
ReverseTheArray( const short *pArrayStart, int nArrayByteLength )
{
short const *pArrayEnd = (pArrayStart + nArrayByteLength);

while(pArrayStart != pArrayEnd)
{
    short tmp = *pArrayStart;
    *pArrayStart = *pArrayEnd;
    *pArrayEnd = tmp;

    pArrayStart++;
    pArrayEnd--;
}
}

Note the last two lines - I would have bet that these were wrong because simply adding 1 to the pointer wouldn't work, you would need to add sizeof(short). But from testing the code it would seem I'm wrong - "pArrayStart++" adds sizeof(short) to the pointer, not 1.

When did this change? Can anyone give me some insight into what I'm wrong about so that I can not look stupid if I'm asked about this?

Edit: Okay - seems like it's always been that way. My bad.

user2226001
  • 89
  • 1
  • 8
  • 4
    Pointer arithmetic has behaved this way for my entire life I believe. – Tavian Barnes Jul 28 '14 at 18:21
  • 4
    `p + sizeof(int)` does not result in `&array[1]`. It results in `&array[sizeof(int)]`. It has been this way since the earliest days of C. – chris Jul 28 '14 at 18:21
  • 1
    "For example, if int* p == array[0], then you'd know that p + sizeof(int) would find array[1]." - no, I would not know because it's not true. Pointer arithmetic in C++ never worked as you claim it works. – The Paramagnetic Croissant Jul 28 '14 at 18:22

1 Answers1

0

The type of pointer is merely for this purpose. "Pointer to int" means adding one would skip 4 bytes (if int is 4 bytes on that machine.

Update: (Of course, in addition to explaining what type of data it is pointing to).

fkl
  • 5,412
  • 4
  • 28
  • 68
  • No, providing size information is not the only purpose of pointers having referenced types. – The Paramagnetic Croissant Jul 28 '14 at 18:24
  • Emm i should have written "in addition to telling what type of data it would point to" will add that. But the point here is, TYPE of pointer is the only source of info telling you how many bytes it would skip – fkl Jul 28 '14 at 18:25