Hi,
In the program below, in the cout statement I want to understand what the code in the (ptr –arr) is doing. I understand ptr is the result of the find algorithm but I don’t know what the –arr does. If you can explain that to me I would appreciate it. I’m sure it is something simple but I don’t remember nor can find it.
Thanks!!
Shanna

// Finds the first object with a specified value

#include <iostream>
#include <algorithm>
using namespace std;

int arr[] = {11, 22, 33, 44, 55, 66, 77, 88};

int main()
{
    int *ptr;
    ptr = find(arr, arr+8, 33);

    cout << "First object with value 33 found at offset " << (ptr -arr) << endl;

    system("pause");
    return 0;
}

Recommended Answers

All 3 Replies

ptr is a pointer to first position in array and arr is pointing to where number 33 exists in array. so (ptr-arr) is the offset from begining of the array where 33 exists (probably equal to 2).

ptr is a pointer to first position in array and arr is pointing to where number 33 exists in array. so (ptr-arr) is the offset from begining of the array where 33 exists (probably equal to 2).

Almost. You have ptr and arr the wrong way round in this explanation :)

In C/C++, an array declared as:

int arr[] = { 5, 4, 3, 2, 1 };

occupies a contiguous block in memory. The variable arr is a pointer to the first byte of this memory block, so to access any of the elements, you can use pointer arithmetic to increment the position of the arr pointer to read out the element you want. In fact when you do something like:

int x = arr[2];

You're using a piece of syntactic sugar. The compiler transforms this into:

int x = *(arr + 2);

In this case, you can see it's says:

  • Get the address of the start of the array:
    arr
  • Move two places forward:
    arr + 2
  • Derefernce the value that you find at this position:
    *(arr + 2)

So, in your example, ptr is set to point at the position with the value 33 in it. arr is always pointing at the start of the block of memory that contains the array (i.e. index 0), so the value of ptr - arr is the index of the value 33 in the array (i.e (arr + 2) - arr = 2).

If you're using a generic, STL container, then you can't always do the kind of arithmetic used here, so in general you should use the std::distance function:

size_t position = std::distance( arr, std::find( arr, arr + 8, 33 ) );

Hav fun :)

Awesome explanation! Thanks a bunch!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.