My background: I didn't read too much about memory allocation through stack and heap, but stack allocation it's 'casually' said to be faster. I think that when you create an object with new
keyword you are using somehow heap allocation, I don't expect it when I just do
A a;
.
Problem:
I'm trying to implement a linked list in C++ with the possibility to insert an element in any position nth. For this I implemented a flag
, that would help control the position, but when i use this declaration the data in my head
pointer changes. I reduced the original code, but the following resumes the problem:
#include <iostream>
struct node {
int data;
node* next;
node* prev;
node(int dat) { data = dat; next = nullptr; prev = nullptr; }
};
struct Linked_list {
node* head;
node* tail;
Linked_list(int data) {
node init(data);
head = &init;
tail = &init;
}
void insert() {
node* iterator = head;
std::cout << head->data;
int flag = 0;
//prints -858993460 if we declare the flag.
//If flag declaration doesn't exist prints 12;
}
};
int main()
{
Linked_list A(12);
A.insert();
}
Why is this happening? I really need to implement it dinamically?