直接打印一个指向字符串的指针一定结果是指针的地址吗?还是这个字符串本身?答案是“看情况”。
- char
*m1 = "coconut is lovely"; - char
*m2 = "passion fruit isnice"; - char
*m3 = "craneberry is fine";
- cout<<"Now
use cout to print *m1="<<*m1<<endl;
输出: Now use cout to print *m1=c;
说明:输出m1指向的字符串的第一位的内容
- cout<<"Now
use cout to print m1="<<m1<<endl;
说明:输出m1所指的内容,而不是m1指向的地址。但是看下面
- 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中如何表现
- printf("Now
use printf to print *m1=%c\n", *m1);
说明:若printf操作*m1,结果为m1指向的字符串的第一位的内容。
注意是%c而不是%s。因为是字符型,而非字符串型。所以以下表达错误: printf("Now use printf to print *m1= %s\n", *m1);
- printf("Now
use printf to print m1=%d\n", m1);
说明: m1是指针,输出m1所指向的地址。上面例子中的cout<<m1输出的是字符串内容。二者不一致,似乎反常了。但是我们可以使得它们行为一致。如下:
- printf("Now
use printf to print m1= %s\n",m1);
说明: m1是指针,输出m1所指向的地址。使用%s而非%d就可以使得m1不去表示地址而去表示字符串内容。
再用下面的例子验证一下:
- 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
- for
(i=0; i<3; i++) - printf("%d\n",
message[i]);
4636884
4636868
4636854
- printf("%d\n",
m1);
输出:
4636884
- printf("%d\n",
m2);
输出:
4636868
- printf("%d\n",
m3);
输出:
4636854