Reputation: 91
I need to use a list of int[2]
. I tried using the list from STL but I'm getting weird results when trying to access the list.
I save all different combinations of [-1,+1]
in the list, but when I try to get one of them, it's always (1,1)
.
Here is my code:
#include <iostream>
#include <list>
using namespace std;
int main (void){
list<int*> test;
int x=0,y=0,i,j,k,l;
int *pin=new int[2];
for (k = x-1; k <= x+1; k++) {
for (l = y-1; l <= y+1; l++) {
pin[0] = k;
pin[1] = l;
cout<<"inserting into list: "<<k<<" "<<l<<endl;
test.push_back(pin);
}
}
while(!test.empty()){
pin=test.back();
std::cout<<"List contains: "<<pin[0]<<" "<<pin[1]<<std::endl;
test.pop_back();
}
}
Upvotes: 0
Views: 5941
Reputation: 105995
You allocated only memory for one int[2]
and you're using the same memory inside of your for loop. Have a look at the following code:
#include <iostream>
#include <list>
using namespace std;
int main (void){
list<int*> test;
int x=0,y=0,i,j,k,l;
int *pin;
for (k = x-1; k <= x+1; k++) {
for (l = y-1; l <= y+1; l++) {
pin = new int[2]; /* allocate memory for each element */
pin[0] = k;
pin[1] = l;
cout<<"inserting into list: "<<k<<" "<<l<<endl;
test.push_back(pin); /* add the address of above allocated memory to the list */
}
}
while(!test.empty()){
pin=test.back();
std::cout<<"List contains: "<<pin[0]<<" "<<pin[1]<<std::endl;
test.pop_back(); /* delete the pointer from the list */
delete[] pin; /* free the allocated memory */
}
}
Upvotes: 1
Reputation: 7164
Ok first of all, why do you need to use an int[2]
in your list? You could as easily use a
std::list<std::vector<int> > test;
or
std::list<std::pair<int,int> > test;
for that matter. However in anyway getting back to your question:
You are allocating storage for your array once here:
int *pin=new int[2];
and you are then entering the loop never allocating new storage.
So every access to pin
like in here
// Loop start
pin[0] = k;
pin[1] = l;
// ...
test.push_back(pin);
// Loop end
Will always refer to the SAME memory location, and you will end up having a list filled all over with the same pointer pointing to the same memory address.
If you had used a list of vectors, that error could not have happened in the first place, if you must allocate the storage, be sure to do it every time the loop body starts. Take absolute care to also DEALLOCATE the allocated storage properly once you are done with the data.
Upvotes: 2
Reputation: 181097
You allocate one single pin with new
, and add it multiple times, just changing the values.
In other words, you add pin to the list, change it and the existing references to the same pin in the list will also change. In the end, all pin's in the list will have the value of the last inserted one.
Upvotes: 3