1 / 10

Arrays & Pointers & Strings

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; }

Download Presentation

Arrays & Pointers & Strings

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays & Pointers & Strings CAS CS210 Ying Ye Boston University

  2. 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)); }

  3. Outline • Arrays • Pointers • Strings

  4. 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};

  5. Arrays • multi-dimensional arrays: 2D: int arr[3][3]; 3D: int arr[3][4][5]; ...... arr[3][3]

  6. 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 == ?

  7. 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;

  8. 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];

  9. 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

  10. 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

More Related