100 likes | 211 Views
Arrays & Pointers & Strings. CAS CS210 Ying Ye. Boston University. isPower2. int Count(unsigned char v) { int num = 0; while(v){ v &= (v - 1); num++; } return num; }
E N D
Arrays & Pointers & Strings CAS CS210 Ying Ye Boston University
isPower2 int Count(unsigned char v) { int num = 0; while(v){ v &= (v - 1); num++; } return num; } For a variable v = xxxx1000(x can be 1 or 0), v - 1 == xxxx0111, so v & (v - 1) == xxxx0000, the '1' in the rightmost is erased. int isPower2(int x) { return ~(x >> 31) & !(x & (x - 1)); }
Outline • Arrays • Pointers • Strings
Arrays • type array_name[size]; e.g. int arr[8]; char abc[3]; int* def[4]; • initial assignment: int arr[2] = {1, 2}; Syntax Error:int arr[2]; arr[2] = {1, 2}; • define without size: int arr[]; ??? int arr[] = {1, 2};
Arrays • multi-dimensional arrays: 2D: int arr[3][3]; 3D: int arr[3][4][5]; ...... arr[3][3]
Pointers • Fixed size: 4 bytes in 32-bit machine, 8 bytes in 64-bit one • Why need the type? (e.g. int *p, type: int) how to access memory: *p • Pointer arithmetic int *p1 = 1000; p1 = p1 + 1; p1 == ? short *p2 = 1000; p2 = p2 + 1; p2 == ? char *p3 = 1000; p3 = p3 + 1; p3 == ?
Pointers • Download http://cs-people.bu.edu/yingy/array.c • Download http://cs-people.bu.edu/yingy/array2.c p = p + 4 * i; *(int *)p; *abc;
Arrays & Pointers • int arr[10]; int *p = arr; Or int *p = &arr[0]; • access element i: *(p + i); Or p[i]; • 2D array: int abc[5][10]; int (*tt)[10] = abc; • access element (i, j): *(*(tt + i) +j); Or tt[i][j];
Arrays & Pointers • Write a small program: initialize a 1D array and a 2D array with some values print out some elements of these arrays using pointers
Strings • "abcd" null-terminated: 5 bytes • char str[5] = {'a', 'b', 'c', 'd', '\0'}; • char str[] = "abcd"; • Download http://cs-people.bu.edu/yingy/string.c