Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to an Element of a Vector

If I have a pointer that is pointing to an element in a vector, say element 2, and then that element gets swapped with element 4 of the same vector. Is the pointer now pointing to element 2, element 4, or neither? Example:

vector a is equal to [1,2,3,4,5]
create pointer that points to the element 2, which is equal to 3 in this case
swap elements 2 and 4
vector a is now [1,2,5,4,3]

where is the vector pointing to?

like image 972
Silvae Avatar asked Jul 07 '10 15:07

Silvae


1 Answers

You mean, "where is the pointer pointing to?". If that's the case, it'll point to the same location in memory as before which is now occupied by the value 5.

Also, by swapping I assume you meant swapping the values between two locations.

Why?

Simply because your pointer points to a memory location. What's stored there doesn't matter --- it could be a value, or it could be garbage. When you dereference it (to see what the value is) it will return the value stored at that location.

Since you've swapped the values, the value at that location is 5 not 3 hence, the pointer is still pointing to the same location and is unchanged but the value at the location has changed.

Sample Code:

// Create the vector
int a[] = {1,2,3,4,5};
int* ptr = &a[2];
// Display original status
std::cout<<"Original Value: "<<*ptr<<std::endl;
std::cout<<"Address: "<<ptr<<std::endl;
// Swap values
std::swap(a[2],a[4]);
// Check 
std::cout<<"New Value: "<<*ptr<<std::endl;
std::cout<<"Address: "<<ptr<<std::endl;

Note:

I've used an array of integers in the example but if by vector you meant std::vector, the same will hold assuming no reallocation has taken place (check out this SO answer).

like image 50
Jacob Avatar answered Oct 20 '22 00:10

Jacob