/* * Program to demonstrate using array(s). * * Defines and prints an array of "random" values and then prompts * user to specify an index to change. * Notice that specifying an index out of range is wrong but may or may * not cause immediate trouble. That's C. */ #include #include /* FIXME? arguably these should both be obtained from the user */ #define ASIZE 10 #define SEED 5 void printarray(int size, int nums[]) { printf("size of array in printarray %d\n", (int) sizeof(nums)); for (int i = 0; i < size; ++i) { printf("nums[%d] is %d\n", i, nums[i]); } } /* alternate version using C99 syntax for VLA argument void printarray(int size, int nums[size]) { printf("size of array in printarray %d\n", (int) sizeof(nums)); for (int i = 0; i < size; ++i) { printf("nums[%d] is %d\n", i, nums[i]); } } */ void fillwithrandom(int size, int nums[]) { srand(SEED); for (int i = 0; i < size; ++i) { nums[i] = rand(); } } int main(void) { int nums[ASIZE]; printf("size of array in main %d\n", (int) sizeof(nums)); fillwithrandom(ASIZE, nums); printarray(ASIZE, nums); printf("enter index\n"); int index; if (scanf("%d", &index) != 1) { printf("invalid\n"); return 1; /* bail out */ } if ((index < 0) || (index >= ASIZE)) { printf("out of bounds -- good luck\n"); } nums[index] = 100; printarray(ASIZE, nums); return 0; }