指向字符串的指针在printf与cout中的表现比较

直接打印一个指向字符串的指针一定结果是指针的地址吗?还是这个字符串本身?答案是“看情况”。

[cpp]  view plain copy
  1. char *m1 "coconut is lovely" 
  2. char *m2 "passion fruit isnice" 
  3. char *m3 "craneberry is fine" 
首先来看在cout如何表现
[cpp]  view plain copy
  1. cout<<"Now use cout to print *m1="<<*m1<<endl;  

 

输出: Now use cout to print *m1=c;

说明:输出m1指向的字符串的第一位的内容

 

[cpp]  view plain copy
  1. cout<<"Now use cout to print m1="<<m1<<endl;  
输出: Now use cout to print *m1= coconut is lovely

 

说明:输出m1所指的内容,而不是m1指向的地址。但是看下面

[cpp]  view plain copy
  1. cout<<"Now use cout to print m1="<<(int)m1<<endl;  

输出: Now use cout to print *m1=4636884

说明:指向字符串的指针m1在cout中默认表达为字符串内容,但是也可用(int)强制表达为地址。这个地址就是字符串”coconut is lovely”的首地址,也是首字符c的首地址。

 

然后来看在sprintf中如何表现

[cpp]  view plain copy
  1. printf("Now use printf to print *m1=%c\n"*m1);    
输出: c

 

说明:若printf操作*m1,结果为m1指向的字符串的第一位的内容。

注意是%c而不是%s。因为是字符型,而非字符串型。所以以下表达错误: printf("Now use printf to print *m1= %s\n", *m1);

[cpp]  view plain copy
  1. printf("Now use printf to print m1=%d\n"m1);     
输出: Now use printf to print m1= 4636884

 

说明: m1是指针,输出m1所指向的地址。上面例子中的cout<<m1输出的是字符串内容。二者不一致,似乎反常了。但是我们可以使得它们行为一致。如下:

[cpp]  view plain copy
  1. printf("Now use printf to print m1= %s\n",m1);     
输出: Now use printf to print m1= coconut is lovely

 

说明: m1是指针,输出m1所指向的地址。使用%s而非%d就可以使得m1不去表示地址而去表示字符串内容

 

再用下面的例子验证一下:

[cpp]  view plain copy
  1. char *m1 "coconut is lovely" 
  2. char *m2 "passion fruit isnice" 
  3. char *m3 "craneberry is fine" 
  4. charmessage[3];                   
  5. int i;                              
  6.                                         
  7. message[0] m1;                    
  8. message[1] m2;                    
  9. message[2] m3;                    
  10.      
  11. for (i=0; i<3; i++)  
  12. printf("%s\n"message[i]);     

输出:

coconut is lovely

passion fruit is nice

craneberry is fine

[cpp]  view plain copy
  1. for (i=0; i<3; i++)  
  2. printf("%d\n"message[i]);          
输出:

 

4636884

4636868

4636854

[cpp]  view plain copy
  1. printf("%d\n"m1);  

输出:

4636884

[cpp]  view plain copy
  1. printf("%d\n"m2); 

输出:

4636868

[cpp]  view plain copy
  1. printf("%d\n"m3);  

输出:

4636854


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值