zoukankan      html  css  js  c++  java
  • 数组字符串与指针字符串的区别 char s[]="***" 和char *s="***"的区别

     

    char s[] = "wangshihui";

    char *s = "wangshihui"; 

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

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

    s是个char array,含11个byte(包含结尾)"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<<"
    ----------
    ";
        for(int i = 0; i != sizeof(s1)-1; ++i)
        {
            cout << s1[i];
        }
        cout<<"
    ----------
    ";
        for(int i = 0; i != strlen(s2); ++i)
        {
            cout << *(s2 + i);
        }
        cout<<"
    ----------
    ";
        while(*s2)
        cout << *s2++;
        cout<<"
    ----------
    ";
        /************
        while(*s1)//编译不通过:lvalue required as increment operand|
        cout << *s1++;
        *************/
    }
    /************************
    size of s1: 11
    size of s2: 4
    
    ----------
    wangshihui
    ----------
    wangshihui
    ----------
    wangshihui
    ----------
    
    **************************/
    


     


  • 相关阅读:
    python json 和 pickle的补充 hashlib configparser logging
    go 流程语句 if goto for swich
    go array slice map make new操作
    go 基础
    块级元素 行内元素 空元素
    咽炎就医用药(慢性肥厚性咽炎)
    春季感冒是风寒还是风热(转的文章)
    秋季感冒 咳嗽 怎么选药
    解决IE浏览器“无法显示此网页”的问题
    常用的 css 样式 记录
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3223532.html
Copyright © 2011-2022 走看看