字符串的简单介绍

来源:互联网 发布:制作菜单的软件 编辑:程序博客网 时间:2024/06/06 03:18
字符串是由若干字符组成的序列,也是面试的常考的重点之一,主要针对于字符串长度的计算考察。在C/C++中,每个字符串都以字符'\0'作为结尾,这样容易帮助我们找到字符串的尾部。但也由于这个特点,每个字符串中都有一个额外的字符开销,一不注意就会造成字符串越界,如:  
char str[10];strcpy(str, "0123456789");
当声明了一个长度为10的字符数组,然后把“0123456789”复制到数组中,但由于“0123456789”末尾还有一个标记字符串结束的标志'\0'作为结尾,故此字符串实际长度为11个字节。要正确复制该字符串,则字符数组也要有11个字节。在C/C++中,常量字符串通常放到单独的一个内存区域中,目的是为了节省内存。当几个指针赋值给相同的常量字符串时,实际上是指向了相同的内存地址。但使用常量内存初始化数组时,情况却有所不同,如:
int main(){    char str1_array[] = "hello world";    char str2_array[] = "hello world";    char* str1_point = "hello world";    char* str2_point = "hello world";    if (str1_array == atr2_array)    {        std::cout << "str1_array and str2_array are same." << std::endl;    }    else    {        std::cout << "str1_array and str2_array are not same." << std::endl;    }    if (str1_point == str2_point)    {        std::cout << "str1_point and str2_point are same." << std::endl;    }    else    {        std::cout << "str1_point and str2_point are not same." << std::endl;    }    return 0;}
str1_array和str2_array是两个字符串数组,并把"hello world"复制到数组中去,由于这是两个初始地址不同的数组,因此str1_array和str2_array的值也不同,故输出为str1_array and str2_array are not same.str1_point和str2_point是两个指针,无须为他分配内存以存储字符串的内容,只需要把"hello world"在内存中的地址赋值给他们即可。由于"hello world"是常量字符串,它在内存中只有一个拷贝,因此str1_point和str2_point指向的是同一个地址,故输出为str1_point and str2_point are same.
1 0