/* * ----------------------------------------------------- * CS2S03/SE2S03, September 2011 * Assignment 2, Question 1 * File: PE0211.cpp * ----------------------------------------------------- * * The program tests the function IndexArray(n) that returns a * pointer to a dynamically allocated integer array with n * elements, each of which is initialized to its own index. * * ----------------------------------------------------- */ #include "genlib.h" #include "simpio.h" #include /* Private function prototypes */ int* IndexArray(int n); /* Main program */ int main() { int *ip; int n; cout << "Enter a positive integer: "; n = GetInteger(); ip = IndexArray(n); if (ip != NULL) { cout << "The elements in the array:" << endl; for (int i = 0; i < n; i++) { cout << " " << ip[i]; } } else { cout << "An empty array."; } cout << endl; return 0; } /* * Function: IndexArray * Usage: ip = IndexArray(n); * ----------------------------------------------------- * This function returns a pointer to a dynamically * allocated integer array with n elements, each of which * is initialized to its own index. * It returns a null pointer if n is not positive. */ int* IndexArray(int n) { if (n <= 0) return NULL; /* Dynamic integer array declaration */ int* myArray = new int[n]; if (myArray == NULL) Error("Fail to allocate memory."); /* initialize the array */ for (int i = 0; i < n; i++) { myArray[i] = i; } return myArray; }