1. local vs. global variable -global variables persist across functions -Local variables: de-allocated when the function returns (local variables are not initialized) - Function arguments are passed by value (like java), aka passed by copying void swap(int x, int y) { //can i declare x again here? 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) } show why this is wrong: Memory can be viewed as an array of bytes Each variable takes up 1, 2, 4 or 8 bytes according to its size (draw picture) in caller x: <1> y: <2> in callee: x: <2> y: <1> 2. Pointer basics Pointers are variables that contain "addresses". int x = 5; int *p; p = &x, (draw picture show address and content) int y; y = *p; //deference the pointer y = (*p) + 10; void swap(int *px, int *py) { int tmp; tmp = *px; *px = *py; *py = tmp; } 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] .... C arrays just refer to a raw region of memory, there's no size information stored anywhere. The name of the array refers to the address of its first element. for (i = 0; i < 10; i++) { a[i] = 0; } int *pa; pa = &a[0]; //equivalent to pa = a; for (i = 0; i < 10; i++) { *pa = 0; pa++; //equivalent to pa = &a[i]; } pa points to the first element (int), pa+1 points to the second element (int), ... so forth. 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. 4. Example. Write a function that multiplies every element of the array by p. void main() { int arr[6]; multiply(...)? // arr should be [2,2,2,2,2,2] //what if i only want to multiply the second half by 2? multiply(...)? } 5. Pointer casting int x[5] = {1,2,3,4,5}; char *p = (char *)x; // what is p[0]? 1 // p[1]? 0 // p[2]? 0 // p[3]? 0 short *z = (short *)(x+1); // z[0]? 2 // z[1] 0 // z[2] 3 // z[3] 0 uses for pointer casting: float x = 0.1; Please write code to display sign-bit, 8-bit exp field, and 23-bit frac field. unsigned int *f = (unsigned int *)(&x); unsigned int sign = (*f) >> 31; unsigned int exp = (*f) << 1 >> 24; unsigned int frac = ((*f) << 9) >> 9; 0 7b 4ccccd Recall floating pointer representation: sign-bit, 8-bit exp field, 23-bit frac field 6. More uses for pointer casting: 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; } }