fork download
  1. //Maxwell Brewer CS1A Chapter 9, p. 537, #1
  2. //
  3. /*******************************************************************************
  4.  * ARRAY ALLOCATOR
  5.  * _____________________________________________________________________________
  6.  * This program will
  7.  * _____________________________________________________________________________
  8.  * INPUT
  9.  *
  10.  *
  11.  * OUTPUT
  12.  *
  13.  *
  14.  ******************************************************************************/
  15.  
  16. #include <iostream>
  17. using namespace std;
  18.  
  19. int *arrayAllocator(int numElements){
  20. //first check if argument is 0 or negative
  21. if(numElements <= 0){
  22. //in this case return a null pointer
  23. return nullptr;
  24. }
  25.  
  26. //otherwise, dynamically allocate memory
  27. //for an array of specified size
  28. int *ptr = new int[numElements];
  29.  
  30. //return the created pointer
  31. return ptr;
  32. }
  33.  
  34. int main() {
  35. int numElements = 70;
  36. int* myArray = arrayAllocator(numElements);
  37.  
  38. if (myArray != nullptr) {
  39. // Use the array (example)
  40. for (int i = 0; i < numElements; i++) {
  41. myArray[i] = i * 2;
  42. }
  43.  
  44. // Print the array
  45. for (int i = 0; i < numElements; i++) {
  46. std::cout << myArray[i] << " ";
  47. }
  48. std::cout << std::endl;
  49.  
  50. // Deallocate memory
  51. delete[] myArray;
  52. } else {
  53. cerr << "Array allocation failed or invalid size." << endl;
  54. }
  55.  
  56. return 0;
  57. }
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