class LinkTest{
public:
LinkTest(){
}
void start(){
List list;
Node * n ;
for(int i = 0; i < 5; i++){
//using pointer
// n = new Node(i);
// list.add(n);
//not using pointer
Node n(i);
list.add(&n);
}
list.displayAll();
}
};
class List{
public:
Node * first, *last;
List(){
first = last = NULL;
}
void add(Node *n){
if(first == NULL){
first = last = n;
}else{
last->next = n;
n->prev = last;
last = n;
}
}
void displayAll(){
while(first != NULL){
first->display();
first =first->next;
}
}
};
I have some experience with Java but I’m new to c++. Here Im doing a linked list test.
If I use a pointer, I’ll have the correct output(0 to 4). But, if I dont use a pointer and just use like a local declaration, the output is like an infinite of 4’s. Can somebody please explain this to me?
If I’m right the local declaration “Node n(i)” will put n to the stack, so does that mean in the next loop n will be replaced with a new n(i+1)? or just n(i+1) will be added to the stack? and why is the output are a bunch of 4’s?
The object you declare here
is a local object of automatic storage, so yes, it exists on the stack, and more specifically, within the local stack frame. It will cease to exist as soon as the local scope ends, which is the end of the for-loop.
But you take the address of that object and put it into a list that lives beyond the current scope. The address will continue to point to some place in the stack, but it will be undefined what is stored there.
So what you see is undefined unbehaviour.