C/C++中的字符串

作者: 李2牛 | 来源:发表于2018-02-28 13:37 被阅读0次

字符串的末尾会有会有\0用于标志着字符串的结束,因此在字符数组的初始化和复制的时候需要防止字符串的越界。如"123456789"中有9个数字如果要存储到字符数组中至少需要10个字节的空间。
代码分析:

#include <iostream>
using namespace std;
int main(){
    char str1[] = "hello alibaba";
    char str2[] = "hello alibaba";
    char* str3 = "hello alibaba";
    char* str4 = "hello alibaba";

    if(str1 == str2)
        cout<< "str2 and str1 are in the same ";
    else 
        cout<<"str1 and str2 are not in the same";
    
    if(str3 == str4)
        cout<< "str3 and str4 are in the same ";
    else 
        cout<<"str3 and str4 are not in the same";
    return 0;
}

对于字符串数组,c/c++会分配两个长度为14字节的空间,并将hello alibaba分别拷贝进去,两个数组的初始地址不同,因此会得到不同的提示。

编译器的警告
而str3和str4是两个指针,系统不会为他们分配内存,只需要让他们指向hello alibaba的内存地址即可,常量字符串在内存中只有一份拷贝,两个指针指向的内容是一致的。

相关文章

网友评论

    本文标题:C/C++中的字符串

    本文链接:https://www.haomeiwen.com/subject/rivbxftx.html