Pages

Friday, June 28, 2013

C++ new operator example

//QUESTION :

/*
Write a program to allocate memory locations for four integer values using ‘new‘operator.

Stores the addresses of allocated memory locations into array of pointers. Find out the

minimum values from four values.
Hint: You will use integer pointer to create integers and array of pointers to store addresses of

integers. You are required to use array of pointers to select minimum value integer.
 
Note: You have to release the memory using delete operator before the end of program.

*/


// CODE :

#include <iostream>
using namespace std;
int main(){

 int *ptr = new int [4];
 cout<<"Enter the values in array\n\n\n\n";
 for (int j = 0; j<4; j++){
  cin >> ptr[j];
 }
 int **arrayOfPtr = new int* [4];
 for (int i = 0; i<4; i++){
  arrayOfPtr[i] = (ptr+i);
 }
 int min = **arrayOfPtr;
 for (int k = 0; k<4; k++){
  if ( min>**(arrayOfPtr+k) ){
   min = **(arrayOfPtr+k);
  }
 }
 cout << "Minimum: "<< min << endl;
 for (i=0; i<4; i++)
  delete arrayOfPtr[i];
 delete [] arrayOfPtr;
 arrayOfPtr = NULL;
 return 0;
}

No comments:

Post a Comment