首页 > 编程语言 > 详细

【C\C++笔记】指针输出字符串

时间:2019-09-19 21:12:20      阅读:63      评论:0      收藏:0      [点我收藏+]

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

 

【C\C++笔记】指针输出字符串

原文:https://www.cnblogs.com/LPworld/p/11552245.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!