【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