tags:

views:

467

answers:

4

I have a pointer to an int.

int index = 3;
int * index_ptr = &index;

index_ptr is a member variable of a class IndexHandler.

class A has a std::vector of IndexHandlers, Avector. class B has a std::vector of pointers to IndexHandlers, Bvector, which I set to point to the items in class A's vector, thusly:

Bvector.push_back(Avector[i].GetPtr())

With me so far?

I want to check that when I resolve the pointers in Bvector, and retreive the internal IndexHandlers index_ptr, that they point to the same index_ptr as class A's...

How can I check they are pointing to the same memory address?... How do i print the address of the value pointed to by both sets of pointers?

+1  A: 

To print the address of an int pointer and the int value an int pointer points to, use

printf("%p %i\n", ptr, *ptr);
schnaader
so %p formats the input as a pointer, thus hex?I've always used %x..
Krakkos
You can also use %d, %i or anything different to format it if you don't like hex format. However, %p seems to be the "correct way" as it doesn't give a compiler warning (using gcc and -Wall).
schnaader
yeah, I need hex, so I've always used %X
Krakkos
+1  A: 

the non-iterator method to print them out side-by-side:

for (size_t i = 0; i < Avector.size(); i++)
{
  std::cout << "Avector ptr:" << Avector[i].GetPtr() << ", Bvector ptr:" << Bvector[i] << std::endl;
}

This will print out the pointer values of each one.

One thing you should be aware of though. If the pointer in the IndexHandler is pointing to a value within the IndexHandler then it can become invalidated if the vector is resized, and pointers to anything above an index WILL be invalidated if an item is inserted or deleted at that index. Because of this, it's generally a bad idea to keep pointers to items in a vector and if you want to do this then it's better practice to use a std::list container instead (which doesn't invalidate pointers to items in the list when you insert or delete new values)

workmad3
except that Bvecotr[i] is actually an IndexHandler*... so I'd need to put `Bvector[i]->GetPtr()`right?
Krakkos
+1  A: 

A very 'C' way to do this would be to use printf. Like this:

printf("A = %p, B = %p", (void *)A, (void *)B);

The above assumes A and B are pointer types.

kbyrd
%p already prints a 0x so in this case you'd get double 0x prefix.
laalto
(On most implementations I have seen. Standard says it's implementation-specific format.)
laalto
Ok, I'll change the answer. I didn't realize different versions of printf did different things.
kbyrd
+1  A: 

How can I check they are pointing to the same memory address?

if (index_ptr1 == index_ptr2)
{
  // They point to the same address
}
else
{
  // They don't
}
Daniel Daranas