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

 

 

首先搞清楚在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



其中解引用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

 

 

另一个博主:https://blog.csdn.net/meng_lemon/article/details/80642938

1. 定义和声明使用的是同一块空间
2. 指针大小是4个字节,数组大小不一定
3. 指针和数组不一样

 

 

补充:类实例化时,用数组声明多个类对象;

classname *p=new classname [5];

p[2].xx();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值