fork download
  1. // Timothy Price CS1A Ch 9 Challenge 1
  2. /******************************************************************************
  3.  * Allocate Array
  4.  *
  5.  * This program dynamically allocates an array and returns an integer array
  6.  * pointer.
  7.  *
  8.  * Inputs:
  9.  * array size
  10.  *
  11.  * Output:
  12.  * array values
  13.  *****************************************************************************/
  14.  
  15. #include <iostream>
  16. #include <iomanip>
  17.  
  18. using namespace std;
  19.  
  20. //function prototype
  21. int* allocateArray(int size);
  22.  
  23.  
  24. int main() {
  25. int count = 5; //constant array size
  26. int* arr = allocateArray(count); //function call
  27.  
  28. if (arr != nullptr) {
  29. for (int i = 0; i < count; ++i) { //loop to populate array
  30. arr[i] = (i + 1) * 10;
  31. }
  32.  
  33. for (int i = 0; i < count; ++i) { //loop to display array
  34. cout << arr[i] << " ";
  35. }
  36.  
  37. delete[] arr; //delete borrowed memory location
  38. arr = nullptr;
  39. }
  40.  
  41. return 0;
  42. }
  43.  
  44. //function definition
  45. int* allocateArray(int size) {
  46. if (size <= 0) {
  47. return nullptr;
  48. }
  49. return new int[size];
  50. }
  51.  
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
10 20 30 40 50