初始化指针时的字符串文字与字符数组 [英] String literals vs array of char when initializing a pointer

查看:30
本文介绍了初始化指针时的字符串文字与字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

灵感来自这个问题.

我们可以用字符串字面量初始化一个char指针:

We can initialize a char pointer by a string literal:

char *p = "ab";

而且完全没问题.可以认为它等价于以下内容:

And it is perfectly fine. One could think that it is equivalent to the following:

char *p = {'a', 'b', '\0'};

但显然事实并非如此.不仅因为字符串文字存储在只读存储器中,而且看起来即使通过字符串文字也具有 char 数组的类型,并且初始化器 {...} 具有 char 数组的类型,两个声明的处理方式不同,因为编译器给出了警告:

But apparently it is not the case. And not only because the string literals are stored in a read-only memory, but it appears that even through the string literal has a type of char array, and the initializer {...} has the type of char array, two declarations are handled differently, as the compiler is giving the warning:

警告:标量初始化器中的元素过多

warning: excess elements in scalar initializer

在第二种情况下.这种行为的解释是什么?

in the second case. What is the explanation of such a behavior?

更新:

此外,在后一种情况下,指针 p 的值将是 0x61(第一个数组元素 'a') 而不是内存位置,这样编译器,正如警告的那样,只取初始化器的第一个元素并将其分配给 p.

Moreover, in the latter case the pointer p will have the value of 0x61 (the value of the first array element 'a') instead of a memory location, such that the compiler, as warned, taking just the first element of the initializer and assigning it to p.

推荐答案

我觉得你很困惑,因为 char *p = "ab";char p[] = "ab"; 语义相似,但含义不同.

I think you're confused because char *p = "ab"; and char p[] = "ab"; have similar semantics, but different meanings.

我相信后一种情况 (char p[] = "ab";) 最好被视为 char p[] = {'a', 'b', '\0'};(用初始化器确定的大小初始化一个数组).实际上,在这种情况下,您可以说 "ab" 并没有真正用作 字符串文字.

I believe that the latter case (char p[] = "ab";) is best regarded as a short-hand notation for char p[] = {'a', 'b', '\0'}; (initializes an array with the size determined by the initializer). Actually, in this case, you could say "ab" is not really used as a string literal.

然而,前一种情况 (char *p = "ab";) 的不同之处在于它简单地初始化了指针 p 以指向它的第一个元素只读字符串文字 "ab".

However, the former case (char *p = "ab";) is different in that it simply initializes the pointer p to point to the first element of the read-only string literal "ab".

我希望你能看到不同之处.虽然 char p[] = "ab"; 可以表示为您描述的初始化,但 char *p = "ab"; 不是,就像指针一样,而不是数组,用数组初始化器初始化它们会做一些完全不同的事情(即给它们第一个元素的值,在您的情况下为 0x61).

I hope you see the difference. While char p[] = "ab"; is representable as an initialization such as you described, char *p = "ab"; is not, as pointers are, well, not arrays, and initializing them with an array initializer does something entirely different (namely give them the value of the first element, 0x61 in your case).

长话短说,C 编译器只在适合的情况下用 char 数组初始值设定项替换"字符串文字,即它用于初始化 char数组.

Long story short, C compilers only "replace" a string literal with a char array initializer if it is suitable to do so, i.e. it is being used to initialize a char array.

这篇关于初始化指针时的字符串文字与字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆