0

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?

3
  • Sorry, as currently phrased this makes no sense to me. Commented Mar 31, 2010 at 17:06
  • 3
    int* pInt = nNums[4]; needs to be int* pInt = &nNums[4];. Commented Mar 31, 2010 at 17:13
  • Good spot. Pseudo code fail. :-) Commented Mar 31, 2010 at 17:25

5 Answers 5

17

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

Sign up to request clarification or add additional context in comments.

Comments

1

Yeah. You take the value of:

pInt - nNums

Comments

1
ptrdiff_t delta = pInt - nNums;

Comments

1

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

Comments

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

2 Comments

Um, NOT the last line. You're assigning the value in nNums[4] to an uninitialized variable.
@JonH, now the address of nNums[4] (type int*) is being assigned to a pointer that is dereferenced (type int). Type mismatch....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.