1. local vs. global variable -global variables persist across functions -Local variables get de-allocated when the function returns void add_one(int x) { x++; } void main() { int x = 10; add_one(x); printf("x is %d\n", x) } //make x into a global variable Let's look at another function void swap(int x, int y) { int tmp = x; x = y; y = tmp; } void main() { int x = 1; int y = 2; swap(x, y); print("x=%d y=%d\n", x, y) } 2. Pointer basics Memory can be viewed as an array of bytes (draw picture |_______________________________|) Each variable takes up 1, 2, 4 or 8 bytes according to its size int x = 5; int *p; p = &x, (draw picture show address and content) int y; y = *p; //deference the pointer y = (*p) + 10; 2. Using pointers as function arguments function arguments are passed by value (like java) Refer back to the swap example: void swap(int x, int y) { int tmp; tmp = x; x = y; y = tmp; } void main() { int x = 1, y = 2; swap(x,y); printf("x=%d, y=%d\n", x, y); } show why this is wrong. in caller x: <1> y: <2> in callee: x: <2> y: <1> show the correct version using pointers void swap(int *x, int *y) in caller: x: <1> y: <2> in callee: px: py: 3. array basics, pointers, pointer arithmetic int a[10]; //array consists of ten consecutive integers a: |________________________________| a[0] a[1] a[2] .... for (i = 0; i < 10; i++) { a[i] = 0; } int *pa; pa = &a[0]; for (i = 0; i < 10; i++) { *pa = 0; pa++; } pa points to the first element (int), pa+1 points to the second element (int), ... so forth. The name of an array is a synonym for the location of its first element. pa = &a[0] is equivalent to pa = a; a+i is equivalent to &a[i] a[i] is equivalent to *(a+i) (*(pa+i) is equivalent to pa[i]) However array name is not a variable, so a++ is ilegal. Note: C arrays just refer to a raw region of memory. It has no size information passing array to function int add_one(int *a, int size) //sometimes, people use int a[], equivalent to int *a ... add_one(a, 10); add_one(a+5,5); //sums the second half //what if callee modifies an element in array? 4. Pointer casting int x[5] = {1,2,3,4,5}; char *p = (char *)x; for (int i = 0; i < 2*sizeof(int); i++) { printf("%d ", *(p+i)); } //x+i == p+i*sizeof(int) int *y; y = (int *)(p + 4); // what's *y? //how about y = (int *)p+4 answer: y = 5 5. generic pointer void * void swap(void *vx, void *vy, int size) { char *x = (char *)vx; char *y = (char *)vy; int i; char tmp; for (i = 0; i < size; i++) { tmp = x[i]; x[i] = y[i]; y[i] = tmp; } }