fork download
  1. //Sam Partovi CS1A Ch. 9, P.537, #1
  2. /*******************************************************************************
  3. * ALLOCATE DYNAMIC ARRAY
  4. * ____________________________________________________________
  5. * This function dynamically allocates an array of integers based on the
  6. * number of elements provided as an argument and returns a pointer to
  7. * the newly allocated array.
  8. * ____________________________________________________________
  9. * INPUT
  10. * numElements: Number of integers to allocate in the array
  11. * OUTPUT
  12. * arrayPtr: Pointer to the dynamically allocated array
  13. *******************************************************************************/
  14.  
  15. #include <iostream>
  16. using namespace std;
  17.  
  18. //Function prototype
  19. int* allocateArray(int numElements);
  20.  
  21. int main() {
  22. int numElements; //INPUT - Number of elements to allocate
  23.  
  24. //Prompt for the number of elements
  25. cout << "Enter the number of elements to allocate: " << endl;
  26. cin >> numElements;
  27.  
  28. //Validate input
  29. while (numElements <= 0) {
  30. cout << "Number of elements must be positive. Try again: ";
  31. cin >> numElements;
  32. }
  33.  
  34. //Call function to allocate array
  35. int* arrayPtr = allocateArray(numElements);
  36.  
  37. //Initialize and display the array contents
  38. for (int i = 0; i < numElements; i++) {
  39. *(arrayPtr + i) = i + 1;
  40. cout << *(arrayPtr + i) << " ";
  41. }
  42. cout << endl;
  43.  
  44. //Free allocated memory
  45. delete[] arrayPtr;
  46.  
  47. return 0;
  48. }
  49.  
  50. //*****************************************************************************
  51. //Function definition for allocateArray: *
  52. //This function dynamically allocates memory for an array of integers *
  53. //based on the number of elements provided and returns a pointer to it. *
  54. //*****************************************************************************
  55. int* allocateArray(int numElements) {
  56. //Allocate memory for the array
  57. int* arrayPtr = new int[numElements];
  58.  
  59. return arrayPtr;
  60. }
  61.  
Success #stdin #stdout 0s 5284KB
stdin
7
stdout
Enter the number of elements to allocate: 
1 2 3 4 5 6 7