tags:

views:

160

answers:

5

Is there a way to figure out where in an array a pointer is?

Lets say we have done this:

int nNums[10] = {'11','51','23', ... };   // Some random sequence
int* pInt = &nNums[4];                     // Some index in the sequence.

...

pInt++;      // Assuming we have lost track of the index by this stage.

...

Is there a way to determine what element index in the array pInt is 'pointing' to without walking the array again?

+17  A: 

Yes:

ptrdiff_t index = pInt - nNums;

When pointers to elements of an array are subtracted, it is the same as subtracting the subscripts.

The type ptrdiff_t is defined in <stddef.h> (in C++ it should be std::ptrdiff_t and <cstddef> should be used).

James McNellis
Good answer, thanks. Didn't realise it was so simple :-)
Konrad
+1  A: 

Yeah. You take the value of:

pInt - nNums
SamB
+1  A: 
ptrdiff_t delta = pInt - nNums;
KTC
+1  A: 

If I'm understanding your question (it's not too clear)

Then

int offset=pInt-nNums;

will give you how far from the beginning of nNums pIint is. If by

int* pInt=nNum[4];

you really meant

int* pInt=nNums+4;

then in

int offset=pInt-nNums

offset will be 4, so you could do

int value=nNums[offset] 

which would be the same as

int value=*pInt
miked
+1  A: 
pInt - nNums

Also,

int* pInt = nNums[4] is probably not what you want. It will point to memory, address of which would be nNums[4]

Change it to

int* pInt = &nNums[4]; 
N 1.1
Um, NOT the last line. You're assigning the value in nNums[4] to an uninitialized variable.
KTC
@KTC I fixed that for him
JonH
@JonH, now the address of nNums[4] (type int*) is being assigned to a pointer that is dereferenced (type int). Type mismatch....
KTC