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