Reputation:
Suppose you have a pointer to an int from an array. Is this the best way to find out which item of the array the pointer points to?
int nmbr = pointer - &array[0];
cout<<"Item number "<<nmbr+1;
If the pointer pointed to the 6th item, would this always print "Item number 6"? Is this error-prone? Is there a faster way to do it? Iterating over the array won't work because of possible duplicate values, but does this always work? In this situation we assume the array starts from item 0 to item x. Is there a situation in which an array's items aren't stored in a continuous line (if the array was initialized as int array[x];
)?
Upvotes: 1
Views: 1132
Reputation: 7017
As mentioned by XTF, yes it is guaranteed to work. There is however, no need for taking the address of the 0'th element, just use array
as it is.
For a more generic solution, that will also work on other containers you could consider the following examples:
#include <iostream>
#include <iterator>
#include <array>
int main()
{
{
int array[10];
int * p = &array[5]; // Somehow get a pointer to the sixth element
std::cout << std::distance(std::begin(array), p) << std::endl;
}
{
std::array<int, 10> array;
int * p = &array[5]; // Somehow get a pointer to the sixth element
std::cout << std::distance(std::begin(array), p) << std::endl;
}
}
Upvotes: 2
Reputation: 36617
Assuming pointer
is known to point at an element of array
, the
std::ptrdiff_t nmbr = pointer - array;
will do it. If pointer does not point at an element of the array, the behaviour is undefined. std::ptrdiff_t
is declared in the standard header <cstddef>
, and is an implementation-defined signed integral type. Using int
is not a good idea, particularly for large arrays, since std::ptrdiff_t
may be able to represent a larger range of values than an int
(and, if the value is larger than an int
can represent, converting the result to int
also gives undefined behaviour).
The +1
s in your code are incorrect, since array indexing in C++ is zero based.
All arrays, in the sense of something declared as
some_type array[some_positive_value];
have contiguous elements. Note that C++ does not support C's VLAs (variable length arrays) i.e. some_positive_value
must be known at compile time.
Upvotes: 3
Reputation: 1101
Both +1's look wrong.. But yes, this is the fastest and simplest way. It's guaranteed to work.
Upvotes: 2