#include /* Written for CS 211 by Pat Troy */ /* forward function declarations - "prototypes" */ void printArray1 (int arr[], int sz); void printArray2 (int* arr, int sz); int main (int argc, char** argv) { /* fixed sized - static array variable */ /* array is allocated on the program stack */ int size = 10; int arr1[size]; int i; /* initialize the array */ for (i = 0 ; i < size; i++) { arr1[i] = i; } /* print out the values in the array */ for (i = 0 ; i < size; i++) { printf ("arri[%d]: %d\n", i, arr1[i]); } /* call the functions */ printArray1 ( arr1, size ); printArray2 ( arr1, size ); /* dynamic array */ /* aray is allocated on the heap */ int* darr; int darrSize = 10; int pos = 0; darr = (int *) malloc (darrSize * sizeof(int) ); /* store the values from 0 to 299 in the dynamic array */ for ( i = 0 ; i < 300 ; i++) { /* check if array is full. If full, grow the array */ if ( pos >= darrSize ) { printf ("\nNeed More Space %d\n", pos); printArray1 ( darr, pos ); /* create a new larger array on the heap */ int* temp; temp = (int*) malloc ( darrSize * 2 * sizeof(int) ); /* copy the existing values to the new larger array */ int j; for ( j = 0 ; j < darrSize ; j++ ) temp[j] = darr[j]; /* deallocate/free the space used by the original array */ free (darr); /* have the variable darr refer to the new larger array */ darr = temp; /* update the current size of the dynamic array */ darrSize = darrSize * 2; } /* put the value in the array */ darr[pos] = i; pos++; } /* call the functions to print the array values */ printArray1 ( darr, pos ); return 1; } /* Note the difference in the type of the first parameter for the following two functions: int arr[] vs int* arr */ void printArray1 (int arr[], int sz) { int i; /* print out the values in the array */ for (i = 0 ; i < sz; i++) { printf ("arr[%d]: %d\n", i, arr[i]); } } void printArray2 (int* arr, int sz) { int i; /* print out the values in the array */ for (i = 0 ; i < sz; i++) { printf ("arr[%d]: %d\n", i, arr[i]); } }