1錯誤代碼
#include<stdio.h> int main(){ char a[]="hello"; char *p=a; for(int i=0;i<5;i++){ printf("%c",*p+i); } return 0; }
輸出
hijkl -------------------------------- Process exited after 0.3297 seconds with return value 0
原因:指針p初始值為a[0],*p是h的地址,h的地址是ascll碼104,而*p+1就是105就是i了(注意*優先級高於+)
---
2正確代碼(其中之一)
#include<stdio.h> int main(){ char a[]="hello"; char *p=a; for(int i=0;i<5;i++){ printf("%c",*(p+i)); } return 0; }
輸出
hello -------------------------------- Process exited after 0.2415 seconds with return value 0
原因:指針p初始值為a[0],*(p+1)的地址是a[1],所以輸出正確
正確代碼2
#include<stdio.h> int main(){ char a[]="hello"; char *p=a; printf("%s",p); return 0; }