fork download
  1. //Cameron Pham CS1A Chapter 9, p. 537, #1
  2. //
  3. /******************************************************************************
  4. * ALLOCATE ARRAY OF INTEGERS
  5. * ______________________________________________________________________________
  6. * This program accepts an integer argument indicating the number of elements to
  7. * allocate. The function dynamically allocates an array of integers.
  8. *******************************************************************************/
  9. #include <iostream>
  10. using namespace std;
  11.  
  12. // Function prototype
  13. int* allocateArray(int size);
  14.  
  15. int main()
  16. {
  17. // Initialize variables
  18. int size; // Number of elements in the array
  19. int* numbers; // Pointer to the dynamically allocated array
  20. // Ask the user for the number of elements
  21. cout << "Enter the number of elements to allocate: ";
  22. cin >> size;
  23. // Allocate the array and receive its address
  24. numbers = allocateArray(size);
  25. // Display the allocated array elements
  26. cout << "Array successfully allocated with "
  27. << size << " elements." << endl;
  28. // Release dynamically allocated memory
  29. delete[] numbers;
  30. numbers = nullptr;
  31. return 0;
  32. }
  33. // Dynamically allocate an integer array and return its pointer
  34. int* allocateArray(int size)
  35. {
  36. int* array = new int[size];
  37. return array;
  38. }
Success #stdin #stdout 0s 544KB
stdin
5
stdout
Enter the number of elements to allocate: Array successfully allocated with 5 elements.