c/c++ 中的字符串以“\0”作为结尾符,这样每个字符串都有一个额外字符的开销。下面代码将造成内存越界。
char str[10]; strcpy(str, “0123456789”);
为了节省内存,c/c++ 会把常量字符串放到单独的一个内存区域。当几个指针赋予相同的常量字符串时,它们实际上会指向相同的内存地址。
char str1[] = "hello world"; char str2[] = "hello world";char *str3 = "hello world"; char *str4 = "hello world";if (str1 == str2)printf("str1 and str2 are same.\n"); elseprintf("str1 and str2 are not same.\n");if (str3 == str4)printf("str3 and str4 are same.\n"); elseprintf("str3 and str4 are not same.\n");
str1和str2是两个字符数组,它们分别占据12个字节的空间,并且分别保存着“hello world”。这是两个起始地址不同的数组,因此str1与str2不相等。第一行输出“str1 and str2 are not same.”。
str3和str4是两个指针,上面已经说到,像这样两个指针赋予相同的常量字符串时,c/c++ 会把常量字符串放到单独的一个内存区域,并且它们都会指向这个相同的内存地址,常量字符串“hello world”在内存中只有一个拷贝。所以str3和str4相等,第二行输出“str3 and str4 are same.”。
【学习资料】 《剑指offer》