1 / 5

程式設計 II

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

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

  3. 指標與字串 • Taiwan • Taiwan • aiwan • iwan • wan • an • n 指標與字串 1 #include<stdio.h> 2 main() 3 { 4 int i, len; 5 char *str = "Taiwan"; 6 printf("%s\n", str); 7 len = strlen(str); 8 for(i = 0; i < len; i++) 9 { 10 printf(str + i);/* str + i是改變字串輸出的起始位 11 printf("\n”); 址,程式執行會從第i個字元開 12 } 始往後輸出字串 */ 13 }

  4. ptr2 ptr1 x (2) (1) 位址200 位址300 8 位址:200 位址:100 位址:300 雙重指標 雙重指標又可以稱做指標中的指標 • 表示方式為: **ptr int x = 8; int *ptr1; int **ptr2; /* ptr2就是所謂的雙重指標表示方式*/ ptr1 = &x; ptr2 = &ptr1;

  5. 雙重指標應用 1 #include<stdio.h> 2 main(){ 4 int i = 5; 5 int *p1; 6 int **p2; 7 p1 = &i; /*指標p1指向i的位址*/ 8 p2 = &p1; /*雙指標p2指向指標p1的位址 */ 9 printf("i = %i &i = %i\n", i, &i); 10 printf("*p1 = %i p1 = %i\n", *p1, p1); 11 printf("**p2 = %i *p2 = %i\n", **p2, *p2); 12 printf("p2 = %p &p1 = %p\n", p2, &p1); 13 } • i = 5 &i = 1245052 • *p1 = 5 p1 = 1245052 • **p2 = 5 *p2 = 1245052 • p2 = 0012FF78 &p1 = 0012FF78

More Related