Search code examples
c++vectordynamic-memory-allocation

C++ pointer problem : How to fix bugs in these codes?


#include <vector>
struct node{
    int x;
};
node* temp = new node();
std::vector<node*> ptrs;
for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
    std::cout << (*j)->x;
}
delete temp;

This prints 999999999 as output. I want to have 123456789.

What is the best way to modify this? I mean, what is the best fashion?


Solution

  • You are allocating only 1 node object and then storing 10 node* pointers into your vector that all point at that 1 node object. So, in your 1st loop, all of the assignments to x are on that 1 node. When that 1st loop is finished, whatever last value was assigned to the 1 node's x, that is what your 2nd loop prints out 10 times.

    For what you are attempting, you need to allocate and free 10 separate node objects, eg:

    #include <vector>
    struct node{
        int x;
    };
    node* temp;
    std::vector<node*> ptrs;
    for (int i = 0; i < 10; ++i){
        temp = new node; // <-- MOVED HERE!!!
        temp->x = i;
        ptrs.push_back(temp);
    }
    std::vector<node*>::iterator j;
    for (j = ptrs.begin(); j != ptrs.end(); ++j){
        std::cout << (*j)->x;
    }
    for (j = ptrs.begin(); j != ptrs.end(); ++j){ // <-- ADD THIS LOOP!!!
        temp = *j;
        delete temp;
    }
    

    But, why are you using pointers at all? This is not a good example that warrants the use of pointers at all. You should create a vector of node objects, not a vector of pointers to node objects, eg:

    #include <vector>
    struct node{
        int x;
    };
    std::vector<node> nodes;
    for (int i = 0; i < 10; ++i){
        node temp;
        temp.x = i;
        nodes.push_back(temp);
    }
    std::vector<node>::iterator j;
    for (j = nodes.begin(); j != nodes.end(); ++j){
        std::cout << j->x; // or (*j).x
    }
    

    Alternatively:

    #include <vector>
    struct node{
        int x;
    };
    std::vector<node> nodes(10);
    std::vector<node>::iterator j;
    for (j = nodes.begin(); j != nodes.end(); ++j){
        j->x = i; // or (*j).x
    }
    for (j = nodes.begin(); j != nodes.end(); ++j){
        std::cout << j->x; // or (*j).x
    }