【C\C++筆記】指針輸出字符串


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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM