fork download
  1. //Diego Martinez CSC5 Chapter 9, P.537, #1
  2. /*******************************************************************************
  3. * ALLOCATE DYNAMIC INTEGER ARRAY
  4. * ______________________________________________________________________________
  5. * This program dynamically allocates an array of integers based on user input.
  6. * It uses a function to create the array in memory and returns a pointer to it
  7. * for use in the main program.
  8. *
  9. * Computation is based on the Formula:
  10. *
  11. * ptr = new int[size];
  12. *
  13. *______________________________________________________________________________
  14. * INPUT
  15. *
  16. * size (number of elements to allocate in the array)
  17. * user-entered values for each array element
  18. *
  19. * OUTPUT
  20. *
  21. * display of the dynamically allocated array contents
  22. *
  23. *******************************************************************************/
  24. #include <iostream>
  25. using namespace std;
  26.  
  27. // Function prototype
  28. int* allocateArray(int size);
  29.  
  30. int main()
  31. {
  32. int size;
  33.  
  34. // Ask user for number of elements
  35. cout << "Enter number of elements to allocate: \n";
  36. cin >> size;
  37.  
  38. // Dynamically allocate array
  39. int* arr = allocateArray(size);
  40.  
  41. // Fill and display array
  42. for (int i = 0; i < size; i++)
  43. {
  44. cout << "Enter value for element " << i + 1 << ": ";
  45. cin >> arr[i];
  46. }
  47.  
  48. cout << "\nArray contents: ";
  49. for (int i = 0; i < size; i++)
  50. {
  51. cout << arr[i] << " ";
  52. }
  53.  
  54. cout << endl;
  55.  
  56. // Free memory
  57. delete[] arr;
  58.  
  59. return 0;
  60. }
  61.  
  62. // Function that allocates array dynamically
  63. int* allocateArray(int size)
  64. {
  65. int* ptr = new int[size];
  66. return ptr;
  67. }
Success #stdin #stdout 0s 5320KB
stdin
3
10
20
30
stdout
Enter number of elements to allocate: 
Enter value for element 1: Enter value for element 2: Enter value for element 3: 
Array contents: 10 20 30