// Copyright 2016 Rajas Agashe // Edited by Sarang Joshi // CSE 351: Section 2 #include // needed for printf #include // needed for boolean values #include // needed for malloc /* * This program is made for you to better understand C's excellent qualities * and quirks. Many different examples from pointer arithmetic to casting * will be covered. */ int main(int argc, char *argv[]) { // 1. Declare pointers: int *x, y; // This line has a bug, causing later code to not type-check! // Look at compiler warnings. // *x = 3; // What happens with this line uncommented and why? x = (int *) malloc(sizeof(int)); // What is allocation? What is initialization? *x = 3; y = x; printf("x = %p, y = %p\n", x, y); // output: x = , y = printf("*&x = %x\n", *&x); // output: *&x = // 2. Some array examples: int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int *ptr = arr; int tmp1 = *(ptr++); int tmp2 = *(++ptr); printf("*(&arr[3] + 2) = %d\n", *(&arr[3] + 2)); // output: *(&arr[3] + 2) = printf("*arr++ = %d\n", tmp1); // output: *arr++ = printf("*++arr = %d\n", tmp2); // output: *++arr = // 3. Checking for null int a = NULL; int b = 351; int *c = NULL; if (c) { printf("c is true?\n"); // output: } if (a || b) printf("true true true\n"); // output: int array[3] = {1, 3, 5}; int ret1 = CheckArray(array, 3); int ret2; // = CheckArray(NULL, 5); printf("ret1 = %d, ret2 = %d\n", ret1, ret2); // output: ret1 = // (commented) ret2 = // (uncommented) ret2 = // 4. Strings char *s1 = "Try changing me."; char s2[] = "I can be changed."; // s1[2] = '4'; // What happens when this is uncommented out? s2[4] = 'd'; printf("%s %s\n", s1, s2); // output: // 5. Unsigned int casting, does the output change on a %u, vs %d? int u1 = -1; unsigned int u3 = (unsigned int)u3; printf("%d %d\n", u1, u3); // output: printf("%u %d\n", u1, u3); // output: } // 6. Consider you have an array and call the CheckArray function. // Will it always work as intended, meaning will it protect from // invalid memory access if the array is null? Hint: Think & vs // && shortcircuiting int CheckArray(int* arr, int len) { if (arr != NULL & arr[len - 1] == 5) { return true; } return false; }