您的位置:首页 > 其它

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

2014-05-14 22:19 344 查看
直接打印一个指向字符串的指针一定结果是指针的地址吗?还是这个字符串本身?答案是“看情况”。

[cpp] view plaincopy

char *m1 = "coconut is lovely";  

char *m2 = "passion fruit isnice";  

char *m3 = "craneberry is fine";  

首先来看在cout如何表现

[cpp] view plaincopy

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

 

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

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

 

[cpp] view plaincopy

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

输出: Now use cout to print *m1= coconut is lovely

 

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

[cpp] view plaincopy

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 plaincopy

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 plaincopy

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

输出: Now use printf to print m1= 4636884

 

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

[cpp] view plaincopy

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 plaincopy

char *m1 = "coconut is lovely";  

char *m2 = "passion fruit isnice";  

char *m3 = "craneberry is fine";  

char* message[3];                   

int i;                              

                                        

message[0] = m1;                    

message[1] = m2;                    

message[2] = m3;                    

     

for (i=0; i<3; i++)  

printf("%s\n", message[i]);     

输出:

coconut is lovely

passion fruit is nice

craneberry is fine

[cpp] view plaincopy

for (i=0; i<3; i++)  

printf("%d\n", message[i]);          

输出:

 

4636884

4636868

4636854

[cpp] view plaincopy

printf("%d\n", m1);  

输出:

4636884

[cpp] view plaincopy

printf("%d\n", m2); 

输出:

4636868

[cpp] view plaincopy

printf("%d\n", m3);  

输出:

4636854
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: