1. 程式人生 > >以下程式的輸出結果是:

以下程式的輸出結果是:

以下程式的輸出結果是:
#include “stdio.h”
main()
{char *s,*s1=“here is”,*s2=“key”;
s=s1;
while (*s1!=’\0’) s1++;
while (*s1++!=*s2++) s2=s;
while (*s2!=’\0’) s2++;
printf ("%d-%d=%d\n",s2,s,s2-s);
}
之前一直不理解這個的結果是什麼意思。。
在這裡插入圖片描述

#include "stdio.h"
main()
{char *s,*s1="here is",*s2="key"; 
s=s1; //從這裡開始,print的s=s1=19748668,即字串儲存起始位置
while (*s1!='\0')	s1++;//s1向後走,直到字串的末尾\0,此時printf的s1=19748675
while (*s1++!=*s2++)	s2=s;
//這行功能:比較s1與s2,s1的“h”(位置為s+1=19748669)與s2的“k”不同,則s2=s
//這行執行後:s1=19748922,s2=19748669
while (*s2!='\0')	s2++; 
//這行讓s2查詢至末尾\0: s2=19748675(*s2="here is")
printf ("s=%d\n",s);
printf ("s1=%d\n",s1);
printf ("s2=%d\n",s2);
printf ("%d-%d=%d\n",s2,s,s2-s);//s2-s即“here is”的長度為7
}

每次執行程式,儲存位置都不一定相同,故s,s1,s2的值每次都會有所不同,但是儲存的相對位置是不會改變的,s2-s即“here is”的長度,為7。