Konrad
Konrad

Reputation: 40947

Array pointer arithmetic question

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?

Upvotes: 0

Views: 589

Answers (5)

N 1.1
N 1.1

Reputation: 12524

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]; 

Upvotes: 1

James McNellis
James McNellis

Reputation: 355049

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

Upvotes: 17

miked
miked

Reputation: 3598

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

Upvotes: 1

KTC
KTC

Reputation: 9003

ptrdiff_t delta = pInt - nNums;

Upvotes: 1

SamB
SamB

Reputation: 9224

Yeah. You take the value of:

pInt - nNums

Upvotes: 1

Related Questions