/***************************************** Sunjay Cauligi, Bryan Martin Section 1 Notes CSE 333 13sp ****************************************/ // questions, comments? // style /**************************************** Clearing up some confusion ****************************************/ // c passes all of its arguments by value // all arguments received are copies // // use pointers to pass by pseudo-reference // // when we say pass-by-reference in c, that means that // a pointer is passed that points to an object, instead of // the object itself /**************************************** Pointers and Addresses ****************************************/ // // declaring a pointer // // type *name; // type *name = address; // // getting and address // // &variable // // address is location in memory // // dereferencing a pointer // *pointer ==> value that is pointed to int x = 42; int *p; // What is p now? p = &x; // What happens here? *p = 99; // Values of p and x? /**************************************** Arrays and pointers ****************************************/ // // An array is just syntactic sugar for a pointer and pointer arithmetic // a[0] <==> *a // a[3] <==> *(a + 3) // // arrays as parameters void f(int a[]); int main(...) { int a[5]; //... f(a); return 0; } // or void f(int *a); int main(...) { int a[5]; //... f(&a[0] <==> a); // what is &a[0] doing? return 0; } /**************************************** Pointer arithmetic ****************************************/ // // pointers are typed // int *int_ptr vs. char *char_ptr int arr[3] = {1, 2, 3}; int *int_ptr = &arr[0]; char *char_ptr = (char *) int_ptr; printf("*int_ptr: %d\n", *int_ptr); // *int_ptr: 1 printf("*char_ptr: %d\n", *char_ptr); // *char_ptr: 1 int_ptr += 1; char_ptr += 1; printf("*int_ptr: %d\n", *int_ptr); // *int_ptr: 2 printf("*char_ptr: %d\n", *char_ptr); // *char_ptr: 0 /**************************************** Function pointers ****************************************/ // // syntax // // return_type (* variable_name)(arguments...) // the star is optional bool forall(int *array, int size, bool (* my_function)(int)) { int i; for (i = 0; i < size; i++) { if (!my_function(array[i])) return false; } return true; } // use typedef to simplify typedef int (*int_comparator)(int, int); void sort(int *arr, int size, int_comparator cmp); /**************************************** In-Place Map Function ****************************************/ // // Example code #include #include #include int main(int argc, char **argv) { // allocate array // map(array, size, function) // print }