# 指標 Pointers.

## Presentation on theme: "指標 Pointers."— Presentation transcript:

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

int a = 5; int * ptr = &a; *ptr = 10; ptr 位址 1236 1240 1244 1248 1252
1256 ?? 1304 a 位址 1296 1300 1304 1308 1312 1316 ?? 10 5

1248 1252 1256 ?? ??

printf(“%s\n”, ptr); // OAO putchar(ptr[1]); // A

for(int i=0; i<100; i++) ptr[i] = i; free(ptr); C++ style: new[], delete[] int *ptr = new int[100]; for(int i=0; i<100; i++) ptr[i] = i; delete [] ptr;

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

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

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])

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

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

pointer to array int (*pa)[20], arr[20]; pa = &arr;

mat[i] = new int[n]; mat[3][n-2] = 8; delete [] mat[i];

for(int i=0; i<n; i++) mat[i] = new int[m]; mat[n-2][m-3] = 100; delete [] mat[i]; delete [] mat;

proc(mat); // error } gcc: cannot convert ‘int(*)[20]’ to ‘int**’