arcanedave

Malloc Bianka

Jan 18th, 2021
673
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <malloc.h>
  5.  
  6. using namespace std;
  7.  
  8. int main () {
  9.    
  10.     int *pointer; //Pointer
  11.     int value; // Variable to store user input
  12.     pointer = (int*) malloc(5*sizeof(int)); //Initiate malloc
  13.     if(!pointer)
  14.     {
  15.         cout << "Memory Allocation Failed"; //Error handling
  16.         exit(1);
  17.     }
  18.     cout << "Please input values!" << endl << endl; // User input values
  19.  
  20.     for (int i=0; i<5; i++) // User must input 5 values, but this can be changed as desired
  21.     {
  22.         cin >> value;
  23.         pointer[i] = value; // Value is stored
  24.     }
  25.     cout << "Your values are..." << endl;
  26.  
  27.     for (int i=0; i<5; i++)
  28.     {
  29.        
  30.         cout << *(pointer+i) << endl; // Output stored values
  31.     }
  32.  
  33.     free(pointer); //Free the memory
  34.     return 0;
  35. }
  36.  
RAW Paste Data