#include #include #include #include // // Purpose: Demonstrate parts of the C/C++ assessment. // // int n[10] = { 5, 3, 7, 6, 15, 8, 10}; int foo1 (int a) { int b, c; c = 0; while (a) { b = a%10; c = c*10 + b; a = a/10; } return c; } int foo2 ( int n[], int nitems) { int j, k; j = n[nitems-1]; for (k = nitems-2; k >= 0; k-- ) { if (j > n[k]) j = n[k]; } return j; } main ( ) { printf("Problem 2: c = %d\n\n", foo1(567)); printf("Problem 3: foo2 = %d\n\n", foo2(n,7)); { // Problem 4 int x = 10; int y = 20; int z; int *px = &x; int *py = &y; z = (*px)++; printf("Problem 4a (z, x): %d, %d\n", z, x); z = (*py) + y; printf("Problem 4b (z, y): %d, %d\n", z, y); printf("Problem 4c: Invalid since x and y are not pointers\n\n"); } { // Problem 5 char s[] = "abcd"; char *p = s; printf("Problem 5\n"); p++; printf("%s ", p); (*p)++; printf("%s ", s); printf("\n\n"); } { // Problem 6 // char *A[] = { "I", "am", "in", "CSE 422S" }; won't work // because the strings are in read-only memory. The following // duplicates each string before assigning it to a char pointer. char *A[] = { strdup("I"), strdup("am"), strdup("in"), strdup("CSE 422S") }; printf("Problem 6a (before): <"); for (int i=0; i<4; i++) printf("%s ", A[i]); printf(">\n"); for (int i=0; i<4; i++) printf("%x ", A[i]); printf("\n\n"); strcpy(A[3], "422S"); printf("Problem 6a (after): <"); for (int i=0; i<4; i++) printf("%s ", A[i]); printf(">\n\n"); strcpy(A[3], "CSE 422S"); // restore value printf("Problem 6b (before): <"); for (int i=0; i<4; i++) printf("%s ", A[i]); printf(">\n\n"); char *B = "422S"; strncpy(A[3], B, strlen(B)); printf("Problem 6b (after): <"); for (int i=0; i<4; i++) printf("%s ", A[i]); printf(">\n\n"); } { // Problem 6 alternative // char *A[] = { "I", "am", "in", "CSE 422S" }; won't work // because the strings are in read-only memory. The following // will allocate space for the 4 by 9 array and then initialize // it with the characters that make up the strings. char A[][9] = { "I", "am", "in", "CSE 422S" }; char *p[] = { &(A[0][0]), &(A[1][0]), &(A[2][0]), &(A[3][0]) }; printf("Problem 6a (before): <"); for (int i=0; i<4; i++) printf("%s ", p[i]); printf(">\n"); for (int i=0; i<4; i++) printf("%x ", p[i]); printf("\n\n"); strcpy(p[3], "422S"); printf("Problem 6a (after): <"); for (int i=0; i<4; i++) printf("%s ", p[i]); printf(">\n\n"); strcpy(p[3], "CSE 422S"); // restore value printf("Problem 6b (before): <"); for (int i=0; i<4; i++) printf("%s ", p[i]); printf(">\n\n"); char *B = "422S"; strncpy(p[3], B, strlen(B)); printf("Problem 6b (after): <"); for (int i=0; i<4; i++) printf("%s ", p[i]); printf(">\n\n"); } }