Posts

Showing posts from September, 2019

Stack vs Heap C++

https://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/ Heap allocation in C++ is done by using new keyword. #include < iostream > #include < vector > using namespace std; struct Node { string tag; vector<Node *> children; }; vector<Node *> nodes; void process(){ for ( int i = 0 ; i< 3 ; i++){ Node* n = new Node() ; n->tag = "a" ; nodes.push_back(n); } } int main() { std::cout << "Hello World!\n" ; process(); for ( int i = 0 ; i< 3 ; i++){ cout<<nodes[i]->tag<<endl; } } above works fine but below will not #include < iostream > #include < vector > using namespace std; struct Node { string tag; vector<Node *> children; }; vector<Node *> nodes; void process(){ for ( int i = 0 ; i< 3 ; i++){ Node n ; // n is allowed on stack and mi...