1 / 7

程式設計 II

程式設計 II. 指標與陣列. 指標與陣列. 一維陣列與指標的關係 當一個指標指向陣列的開頭時,也就是指標指向陣列的起始位址,表示式如下:. char array[10]; ptr = &array[0];. ptr /* ptr 指向陣列開頭位址* /. 100. 一個 char ,佔一個 byte. 指標與一維陣列. 1 #include<stdio.h> 2 main(){ 4 int i; 5 char array[5] = {'A', 'B', 'C', 'D', 'E'};

Download Presentation

程式設計 II

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. 程式設計II 指標與陣列

  2. 指標與陣列 • 一維陣列與指標的關係 • 當一個指標指向陣列的開頭時,也就是指標指向陣列的起始位址,表示式如下: char array[10]; ptr = &array[0]; ptr /* ptr指向陣列開頭位址*/ 100 一個char,佔一個byte

  3. 指標與一維陣列 1 #include<stdio.h> 2 main(){ 4 int i; 5 char array[5] = {'A', 'B', 'C', 'D', 'E'}; 6 7 for(i = 0; i < 5; i++) { 9 printf("*(array + %i) = %c\n", i, *(array + i)); 10 } 11 } *(array + 0) = A *(array + 1) = B *(array + 2) = C *(array + 3) = D *(array + 4) = E

  4. 指標與二維陣列 二維陣列取值時,需要使用兩個中括弧。 • 宣告二維陣列array[2][3]如下表:共有二列及三行

  5. 指標與二維陣列範例 • *(p + 0) = 10 • *(p + 1) = 20 • *(p + 2) = 30 • *(p + 3) = 40 • *(p + 4) = 50 • *(p + 5) = 60 1 #include<stdio.h> 2 main(){ 4 int i, *p; 5 int a[2][3] = {{10, 20, 30}, {40, 50, 60}}; 6 p = a; /* 指標p指向陣列a的起始位址 */ 7 for(i = 0; i < 6; i++) 8 printf("*(p + %i) = %i\n”, i, *(p + i)); 9 }

  6. 雙指標與二維陣列範例 1 #include<stdio.h> 2 main() 3 { 4 int i, **p; 5 int a[2][3]={{10, 20, 30}, {40, 50, 60}}; 6 *p = &a[0]; 7 *(p + 1) = &a[1]; • for(i = 0; i < 3; i++) • printf("*(*p + %i) = %i, *(*(p + 1) + %i) = %i\n”, i, *(*p + i), i , *(*(p + 1) + i)); /*將陣列第一維的a[0]給指標p來指,另一維的a[1]給 指標(p+1)來指,依此類推即可分別得到陣列內的6個值 */ 10 } • *(*p + 0) = 10, *(*(p + 1) + 0) = 40 • *(*p + 1) = 20, *(*(p + 1) + 1) = 50 • *(*p + 2) = 30, *(*(p + 1) + 2) = 60

  7. 指標與字串 • 字串可稱為字元陣列 • 宣告字串可以使用兩種方式,如下表示: • 一般以第一種方式來宣告,宣告字串可以使用指標表示法,方式如下: • 上式宣告告訴編譯器去做兩件事: 1. 保留2bytes的記憶體空間給指標s。 2. 將指標s指向字串的起始位址。 char s1[ ] = "Taiwan”; char s2[ ] = {‘T’, ‘a’, ‘i’, ‘w’, ‘a’, ‘n’, ‘\0’}; char *s = "Taiwan”

More Related