指向字符串的指針在printf與cout區別

 

根據指針用法* 定義一個指針, &變量地址ios

 

int b = 1;測試

 

int *a = &b;ui

 

*a =1,但對於字符串而言並不是如此直接打印指向字符串的指針打印的是地址仍是字符串自己,具體看狀況spa

 

定義:.net

 

char *m1 = "coconut is lovely";  指針

 

char *m2 = "passion fruit isnice";  code

 

char *m3 = "craneberry is fine";  blog

注:實際聲明應該是const char *m1,緣由char *背後的含義是:給我個字符串,我要修改它,此處應該是要讀取它,具體參考ci

 

 

測試輸出:字符串


cout 打印*m1:

 

cout<<"Now use cout to print *m1="<<*m1<<endl;

 

打印輸出:

 

Now use cout to print *m1=c

 

輸出m1指向字符串的第一個字符

 

cout打印m1:

 

cout<<"Now use cout to print m1="<<m1<<endl;

 

輸出

 

Now use cout to print m1=coconut is lovely

 

輸出m1所指的內容,而不是m1指向的地址

 

 

printf打印%c\n", *m1

 

printf("Now use printf to print *m1=%c\n", *m1);

 

輸出:

 

Now use printf to print *m1=c

 

m1指向的字符串的第一位的內容注意是%c而不是%s。由於是字符型,而非字符串型。因此如下表達錯誤: printf("Now use printf to print *m1= %s\n", *m1);

 

printf 打印 %d m1

 

printf("Now use printf to print m1=%d\n", m1);

 

輸出:

 

Now use printf to print m1=4197112

 

m1是指針,輸出m1所指向的地址。上面例子中的cout<<m1輸出的是字符串內容。兩者不一致,彷佛反常了。可是咱們能夠使得它們行爲一致。以下:

 

printf打印%s m1

 

printf("Now use printf to print m1= %s\n",m1);

 

輸出

 

Now use printf to print m1= coconut is lovely

 

m1是指針,輸出m1所指向的地址。使%s而非%d就能夠使得m1不去表示地址而去表示字符串內容

 

 

 

完整例子:

#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
    char *m1 = "coconut is lovely";  
    char *m2 = "passion fruit isnice";  
    char *m3 = "craneberry is fine";
    char* message[3];                   
    int i;                              

    //cout *m1
    cout<<"Now use cout to print *m1="<<*m1<<endl; 
    //cout m1
    cout<<"Now use cout to print m1="<<m1<<endl;
    //cout (int)m1: 64位機char*類型大小位8B,用long轉換
    cout<<"Now use cout to print m1="<<(int)m1<<endl;
    //printf %c *m1
    printf("Now use printf to print *m1=%c\n", *m1); 
    //printf %s *m1
    // printf("Now use printf to print m1= %s\n",*m1); 
    //printf %d m1 
    printf("Now use printf to print m1=%d\n", m1); 
    //printf %s m1
    printf("Now use printf to print m1= %s\n",m1); 
    /*                                       
    message[0] = m1;                    
    message[1] = m2;                    
    message[2] = m3;                    
         
    for (i=0; i<3; i++)  
    printf("%s\n", message[i]); 
    */
}


輸出:

Now use cout to print *m1=c
Now use cout to print m1=coconut is lovely
Now use cout to print m1=4197320
Now use printf to print *m1=c
Now use printf to print m1=4197320
Now use printf to print m1= coconut is lovely

 

 

 

 

 

Ref:

 

  1. http://blog.csdn.net/feliciafay/article/details/6818009
相關文章
相關標籤/搜索