Pages

Thursday, April 24, 2025

Dynamic Memory Allocation - Vectors in C++

#include <iostream>

using namespace std;


void funcInt() {

    int *ptr = new int;

    *ptr = 5;

    cout << *ptr << endl;   

    delete ptr;  -> deletes dynamically memory allocated to prevent memory leaks.

}


void func() {

    int size;

    cin >> size;


    int *arr = new int[size];


    int x = 1;

    for (int i = 0; i < size; i++) {

        arr[i] = x;

        cout << arr[i] << " ";

        x++;

    }

    cout << endl;


    delete[] arr; // correctly deallocating dynamic array

}


int main() {

    funcInt();

    func();

    return 0;

}


No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...