fork download
  1. //Maxwell Brewer CS1A Chapter 9, p. 537, #1
  2. //
  3. /*******************************************************************************
  4.  * ARRAY ALLOCATOR
  5.  * _____________________________________________________________________________
  6.  * This program dynamically allocates an array of integers based on a
  7.  * pre-determined number of elements. After allocation, it initializes
  8.  * each element in the array with a value, demonstrates usage by printing the
  9.  * values, and then deallocates the memory to prevent memory leaks.
  10.  * _____________________________________________________________________________
  11.  * INPUT
  12.  * numElements : Number of elements the user wishes to allocate for the array.
  13.  *
  14.  * OUTPUT
  15.  * Array values : Displays each element in the array after initializing it.
  16.  *
  17.  * ****************************************************************************/
  18.  
  19. #include <iostream>
  20. using namespace std;
  21.  
  22. int *arrayAllocator(int numElements){
  23. //first check if argument is 0 or negative
  24. if(numElements <= 0){
  25. //in this case return a null pointer
  26. return nullptr;
  27. }
  28.  
  29. //otherwise, dynamically allocate memory
  30. //for an array of specified size
  31. int *ptr = new int[numElements];
  32.  
  33. //return the created pointer
  34. return ptr;
  35. }
  36.  
  37. int main() {
  38. int numElements = 70;
  39. int* myArray = arrayAllocator(numElements);
  40.  
  41. if (myArray != nullptr) {
  42. // Use the array (example)
  43. for (int i = 0; i < numElements; i++) {
  44. myArray[i] = i * 2;
  45. }
  46.  
  47. // Print the array
  48. for (int i = 0; i < numElements; i++) {
  49. cout << myArray[i] << " ";
  50. }
  51. cout << endl;
  52.  
  53. // Deallocate memory
  54. delete[] myArray;
  55. } else {
  56. cerr << "Array allocation failed or invalid size." << endl;
  57. }
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0.01s 5280KB
stdin
stdout
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 104 106 108 110 112 114 116 118 120 122 124 126 128 130 132 134 136 138