/* arrDemo1.c author: Mark Stehlik purpose: to demo - various forms of declaring arrays - passing arrays to functions - value and reference parameters */ #include #include #define ARRAY_MAX 5 int getInts(int *a, int *b); void swapInts(int *a, int *b); void copyArray(int a[], int aLen, int b[], int bLen); void swapArrays(int a[], int aLen, int b[], int bLen); void printArray(int arr[], int arrLen); int main(int argc, char *argv[]) { int a[] = {2,3,5,7,11}; /* these values CAN be changed later on */ int b[] = { 4,6,8, 12, 16 }; int c[10], d[7]; printf("\nBefore array swap swap:\n"); printf("a = "); printArray(a, ARRAY_MAX); /* we pass just the array's name. No []s */ printf("b = "); printArray(b, ARRAY_MAX); swapArrays(a, ARRAY_MAX, b, ARRAY_MAX); /* Note we don't use & before the array variable names since an array's name is the start address of array, the address of the first element */ printf("\nAfter array swap:\n"); printf("a = "); printArray(a, ARRAY_MAX); printf("b = "); printArray(b, ARRAY_MAX); printf("\nEnter 2 values on line for c[0] and d[0]: "); scanf("%d %d", c, d); /* it's a good idea to check that scanf returned what you wanted */ /*if (getInts(c, d) != 0) exit(1);*/ printf("c[0]: %d\nd[0]: %d\n", c[0], d[0]); return 0; } /* GETINTS: prompts for and returns 2 ints return value of 0 means both ints successfully gotten from kbd any other value indicates an error. */ int getInts(int *a, int *b) { printf("\nEnter two ints sep. by whitespace: "); return scanf("%d %d", a, b) - 2; } /* SWAPINTS: uses addresses/pointers to exchange values of incoming arguments */ void swapInts(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } /* copyArray: assuming a and b are the same length, copies the corresponding values of a into b */ void copyArray(int a[], int aLen, int b[], int bLen) { int i; if (aLen != bLen) return; /* don't try to copy different sized arrays */ for (i = 0; i < aLen ; i++) b[i] = a[i]; } /* swapArrays: assuming a and b are the same length, swaps the corresponding values of a and b */ void swapArrays(int a[], int aLen, int b[], int bLen) { int i; if (aLen != bLen) return; /* don't try to swap different sized arrays */ for (i = 0; i < aLen ; i++) swapInts(&a[i], &b[i]); /* RE-USE working code since array elements are int variables */ } void printArray(int arr[], int arrLen) { int i; for (i = 0; i < arrLen; i++) printf( "%3d ", arr[i]); printf("\n"); }