1 / 19

Pointers

指標. Pointers. int a = 5; int * ptr ; // pointer to int ptr = &amp; a; // 取 a 位址 // int * ptr = &amp;a; * ptr = 10; // 設定指向位址的值 printf (“a = %d<br>”, a); // a = 10. int a = 5; int * ptr = &amp; a; * ptr = 10;. ptr. 1304. a. 5. 10. 小心. int * a , b; // X: b is int !!

sadah
Download Presentation

Pointers

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. 指標 Pointers

  2. int a = 5; int* ptr; // pointer to int ptr = &a; // 取a位址 // int *ptr = &a; *ptr = 10; // 設定指向位址的值 printf(“a = %d\n”, a); //a = 10

  3. int a = 5; int* ptr = &a; *ptr = 10; ptr 1304 a 5 10

  4. 小心 int* a, b; // X: b is int!! int*a, *b; // O

  5. 小心 int*ptr; … *ptr = 10; Segmentation fault ptr ??

  6. 好習慣 int*ptr=NULL; … if(ptr==NULL){ /* error */ } else *ptr = 10;

  7. 指標&陣列 char s[16]; char *ptr = s; // 相當於ptr = &s[0]; strcpy(s, “OAO”); printf(“%s\n”, ptr); // OAO putchar(ptr[1]); // A

  8. 動態記憶體配置 C style: malloc(), free() int *ptr = malloc(100*sizeof(int)); for(inti=0; i<100; i++) ptr[i] = i; free(ptr); C++ style: new[], delete[] int *ptr = newint[100]; for(inti=0; i<100; i++) ptr[i] = i; delete [] ptr;

  9. 小心 intarr[100]; memset(arr, 0, sizeof(arr)); // sizeof(arr) == sizeof(int[100]) // (400 bytes) int *ptr = new int[100]; memset(ptr, 0, sizeof(ptr)); // sizeof(ptr) == sizeof(int*) // (4 bytes)

  10. struct struct XD { int a, b; }; XD xd; xd.a = 2; XD *ptr = &xd; ptr->b = 3; // or (*ptr).b

  11. 你可以… void my_strcpy(char *dst, char *src) { for(; *src!=‘\0’; dst++, src++) *dst = *src; } char s1[16], s2[16]; scanf(“%s”, s2); my_strcpy(s1, s2); // my_strcpy(&s1[0], &s2[0])

  12. pointer to pointer int**pp, *p, a; p = &a; pp = &p;

  13. array of pointers int*pa[20], n; pa[2] = &n;

  14. pointerto array int(*pa)[20], arr[20]; pa = &arr;

  15. 你可以… int *mat[20], n; scanf(“%d”, &n); for(int i=0; i<20; i++) mat[i] = new int[n]; mat[3][n-2] = 8; for(int i=0; i<20; i++) delete [] mat[i];

  16. 你可以… int **mat, n, m; scanf(“%d%d”, &n, &m); mat = new int*[n]; for(int i=0; i<n; i++) mat[i] = new int[m]; mat[n-2][m-3] = 100; for(int i=0; i<n; i++) delete [] mat[i]; delete [] mat;

  17. 你不可以… void proc(int**mat){ mat[2][3] = 5; } int main() { … int mat[20][20]; proc(mat); // error } gcc: cannot convert ‘int(*)[20]’ to ‘int**’

  18. 你可以… void proc(int(*mat)[20]); void proc(int mat[20][20]); ***不建議***

  19. 結語 • 善用指標,可以讓程式更簡潔易懂、更好維護 • 亂用指標 → 輕鬆RE

More Related