且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串指针和字符串数组的区别

更新时间:2022-06-22 05:39:07

你看到字符串字面量就是你在"中写的字符串.对于每个这样的字符串,无论它在哪里使用,都会自动分配一个全局空间来存储它.当你将它分配给一个数组时——你将它的内容复制到一个新的内存中,即数组的内存中.否则,您只需存储一个指向它的全局内存存储的指针.

You see string literals are the strings you write in "". For every such string, no-matter where it is used, automatically a global space is alloacted to store it. When you assign it to an array - you copy it's content into a new memory, that of the array. Otherwise you just store a pointer to it's global memory storage.

所以这个:

int main()
{
    const char *str= "team_name=fenerbahce";
}

等于:

const char __unnamed_string[] { 't', 'e', /*...*/, ' ' };

int main()
{
   const char *str= __unnamed_string;
}

而当把字符串赋值给数组时,像这样:

And when assigning the string to array, like this:

int main()
{
    char str[] = "team_name=fenerbahce";
}

到这里:

const char __unnamed_string[] { 't', 'e', /*...*/, ' ' };
    
int main()
{
       char str[sizeof(__unnamed_string) / sizeof(char)];
       
       for(size_t i(0); i < sizeof(__unnamed_string) / sizeof(char); ++i)
          str[i] = __unnamed_string[i];
}

如您所见,这是有区别的.在第一种情况下,您只存储一个指针,而在第二种情况下,您将整个字符串复制到本地.

As you can see there is a difference. In the first case you're just storing a single pointer and in the second - you're copying the whole string into local.

注意:字符串文字是不可编辑的,因此您应该将它们的地址存储在一个常量中.

Note: String literals are un-editable so you should store their address at a constant.

在 N4296 - § 2.13.5 .8 中指出:

In N4296 - § 2.13.5 .8 states:

普通字符串字面量和 UTF-8 字符串字面量也被引用作为窄字符串文字.窄字符串文字的类型为数组n const char",其中 n 是字符串的大小,定义如下,并且具有静态存储持续时间

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type "array of n const char", where n is the size of the string as defined below, and has static storage duration

这个决定背后的原因可能是因为这样,这样的数组可以存储在只读段中,从而以某种方式优化程序.有关此决定的更多信息参见.

The reason behind this decision is probably because this way, such arrays can be stored in read-only segments and thus optimize the program somehow. For more info about this decision see.

注1:

在 N4296 - § 2.13.5 .16 中规定:

In N4296 - § 2.13.5 .16 states:

评估一个字符串文字会产生一个字符串文字对象静态存储持续时间,从给定字符初始化为如上所述.

Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above.

这正是我所说的 - 对于每个字符串文字,都会使用它们的内容创建一个未命名的全局对象.

Which means exactly what I said - for every string-literal an unnamed global object is created with their content.