Dynamic Memory Allocation in C++ Part – 3

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// Dynamic memory in CPP
#include <iostream>
#include <cstring> // for strcpy
using namespace std;
class Student 
{
   private:
    char* name;
    int* marks;
    int numSubjects;

    public:
    // Constructor
    Student(const char* studentName, int subjects)    // vivek  5 
    {
        numSubjects = subjects;

        // Allocate memory for name
        name = new char[strlen(studentName) + 1];
        strcpy(name, studentName);

        // Allocate memory for marks array
        marks = new int[numSubjects];

        // Input marks
        for (int i = 0; i < numSubjects; i++) 
        {
            cout << "Enter marks for subject " << i + 1 << ": ";
            cin >> marks[i];
        }
    }

    // Function to display student data
    void display() 
    {
        cout << "\nStudent Name: " << name << endl;
        cout << "Marks: ";
        for (int i = 0; i < numSubjects; i++) 
        {
            cout << marks[i] << " ";
        }
        cout << "\n";
    }

    // Destructor
    ~Student() 
    {
        delete[] name;
        delete[] marks;
        cout << "Memory released for " << name << "\n";
    }
};

int main() 
{
     system("cls");
    int subjects;
    char name[100];

    cout << "Enter student name: ";
    cin.getline(name, 100);
    cout << "Enter number of subjects: ";
    cin >> subjects;
    // Clear buffer before passing to constructor
    cin.ignore();

    // Create student object
    Student s(name, subjects);    //vivek  5
    s.display();
  return 0;
}

 

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *