Answer to Question #186776 in C++ for Ishan

Question #186776

Often some situation arises in programming where data or input is dynamic in nature, i.e.

the number of data item keeps changing during program execution. A live scenario where the

program is developed to process lists of employees of an organization. The list grows as the

names are added and shrink as the names get deleted. With the increase in name the memory

allocate space to the list to accommodate additional data items. Such situations in programming

require which technique. Explain the concept with the help of suitable examples.


1
Expert's answer
2021-05-01T15:29:04-0400

Such situations in programming require Dynamic Memory allocation technique.

Example :


#include <iostream>
using namespace std;
  
int main ()
{
    
    int* p = NULL;
  
    
    
    p = new(nothrow) int;
    if (!p)
        cout << "allocation of memory failed\n";
    else
    {
        // Store value at allocated address
        *p = 29;
        cout << "Value of p: " << *p << endl;
    }
  
    
    
    float *r = new float(75.25);
  
    cout << "Value of r: " << *r << endl;
  
    
    int n = 5;
    int *q = new(nothrow) int[n];
  
    if (!q)
        cout << "allocation of memory failed\n";
    else
    {
        for (int i = 0; i < n; i++)
            q[i] = i+1;
  
        cout << "Value store in block of memory: ";
        for (int i = 0; i < n; i++)
            cout << q[i] << " ";
    }
  
  
    delete p;
    delete r;
  
    
    delete[] q;
  
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS