数组字符串与指针字符串的区别 char s[]="***" 和char *s="***"的区别

 

char s[] = "wangshihui";

char *s = "wangshihui"; 

皆宣告了s字符串,在C-style string的函数皆可使用,但两者背后意义却不相同。

char s[] = "wangshihui";   s指向栈内存

s是个char array,含11个byte(包含结尾\0)"wangshihui"s来说是initializer,将字符一个一个地copys阵列。

char *s = "wangshihui";   s指向文字常量区,指向的内容为const  相当于const char *s="wangshihui"

s是一个pointer指向char,由于"wangshihui"本身就是一个string literal,所以s指向"wangshihui"这个string literal的起始存储器位置。



 char s1[] = "wangshihui";

 char *s2 = "wangshihui";

 cout << "size of s1: " << sizeof(s1) << endl;

 cout << "size of s2: " << sizeof(s2) << endl;

s1是字符串数组,所以占了11byte(包含字符串结束标志);

s2只是pointer,所以占了4 byte

实际使用有什么不同吗?两种写法皆可使用substringpointer写法,但只有char *s可以直接使用*s++写法。

char s[]为阵列,虽然s == &s[0],但s是『常数』,恒等于&s[0]无法改变,但char *spointer,指向s[0],但却是变量,可以任意改变,故可用*s++任意更改pointer值。 

Conclusion

一般人很少分辨char s[]char *s的差异,大部分状况下用法相同,但char *s速度略快,因为不需copy的动作,且*s++C语言常用的写法。

#include <iostream>
#include <cstring>
using namespace std;

int main()
    {
    char s1[] = "wangshihui";
    char *s2 = "wangshihui";
    cout << "size of s1: " << sizeof(s1) << endl;
    cout << "size of s2: " << sizeof(s2) << endl;
    cout<<"\n----------\n";
    for(int i = 0; i != sizeof(s1)-1; ++i)
    {
        cout << s1[i];
    }
    cout<<"\n----------\n";
    for(int i = 0; i != strlen(s2); ++i)
    {
        cout << *(s2 + i);
    }
    cout<<"\n----------\n";
    while(*s2)
    cout << *s2++;
    cout<<"\n----------\n";
    /************
    while(*s1)//编译不通过:lvalue required as increment operand|
    cout << *s1++;
    *************/
}
/************************
size of s1: 11
size of s2: 4

----------
wangshihui
----------
wangshihui
----------
wangshihui
----------

**************************/


 


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值