码迷,mamicode.com
首页 > 编程语言 > 详细

c与c++中输出字符指针和字符串指针的问题

时间:2018-07-22 20:47:17      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:[]   第一个字符   表示   size   test   int   style   c++   return   

首先搞清楚在c语言中没有字符串的类型,所以对字符串操作,有两种形式:可以用字符指针,或者字符串数组(这里的指针变量c,系统会为其重新分配内存。

c程序示例:

  1  #include <stdio.h>
  2
  3 int main()
  4 {
  5   char *a="hello";
  6   char b[]={‘l‘,‘i‘,‘n‘,‘u‘,‘x‘};
  7   char *c=&b[1];
  8
  9    printf("%c\n",*a);
 10   printf("%s\n",a);
 11   printf("%s\n",c);
 12   printf("%s\n",b);
 13   printf("%c\n",*c);
 14  return 0;
 15 }

执行效果如下:

[lm@lmslinux ~]$ ./cp
h
hello
inux
linux
i
4



其中解引用a时,输出指针指向的第一个字符 “h”,而printf(“%s\n”,a)时因为规定了输出字符串的格式,所以不会输出c的地址,而是“hello”这个字符串。 printf("%d\n",a)时则输出十进制的c指向的地址。

c++程序示例:

 1 #include <iostream>
  2 #include <stdio.h>
  3 #include <string.h>
  4 using namespace std;
  5
  6 int main()
  7 {
  8     string s ="string";
  9     string *p=&s;
 10     char * c="hello";
 11     cout<<*c<<endl;
 12     cout<< c<<endl;
 13     cout<<s<<endl;
 14     cout<<*p<<endl;
 15     cout<<p<<endl;
 16     return 0;    
 17 }
cout输出时是自动判断输出的格式,而且有 string 来表示字符串,*p 解引用输出的是整个字符串,而 p 输出的是字符串的首地址。在cout<<c 时自动判定为输出字符串, * c 解引用c时 输出字符串的第一个字符 “h”。

执行结果:[lm@lmslinux ~]$ ./test
h
hello
string
string
0x7fff97664730

 

c与c++中输出字符指针和字符串指针的问题

标签:[]   第一个字符   表示   size   test   int   style   c++   return   

原文地址:https://www.cnblogs.com/sanerer/p/9351189.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!