char* 和 char arr[] 区别 - C++/C
刚开始使用 C++,我想知道是否有人可以解释一下.
Just starting out in C++, I was wondering if someone could explain something.
相信你可以通过以下方式初始化一个char数组
I believe you can initialise a char array in the following way
char arr[] = "Hello"
这将创建一个具有值 'H'、'e'、'l'、'l'、'o'、''
的 Char 数组.
This will create a Char array with the values 'H', 'e', 'l', 'l', 'o', ''
.
但如果我确实创建了这个:
But if I do create this:
char* cp = "Hello";
这会创建一个数组以及指向该数组的指针吗?
Will that create an array, and the pointer to that array?
例如:cp
会指向内存中的第一个元素('H')
,还有数组的附加元素?
Eg: cp
will point to the first element ('H')
in memory, with the additional elements of the array?
推荐答案
字符串字面量本身就是数组类型.因此,在您给出的第一个示例中,实际上涉及两个数组.第一个是包含字符串文字的数组,第二个是您要声明的数组 arr
.字符串文字中的字符被复制到 arr
中.C++11 的措辞是:
The string literal itself has array type. So in the first example you gave, there are actually two arrays involved. The first is the array containing the string literal and the second is the array arr
that you're declaring. The characters from the string literal are copied into arr
. The C++11 wording is:
char
数组(无论是纯 char
、signed char
还是 unsigned char
)、char16_t
数组、char32_t
数组或 wchar_t
数组可以由窄字符文字、char16_t
字符串文字、 初始化char32_t
字符串文字或宽字符串文字,或用括号括起来的适当类型的字符串文字.字符串字面量值的连续字符初始化数组的元素.
A
char
array (whether plainchar
,signed char
, orunsigned char
),char16_t
array,char32_t
array, orwchar_t
array can be initialized by a narrow character literal,char16_t
string literal,char32_t
string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces. Successive characters of the value of the string literal initialize the elements of the array.
在第二个示例中,您让字符串字面量数组进行数组到指针的转换以获取指向其第一个元素的指针.所以你的指针指向字符串字面量数组的第一个元素.
In the second example, you are letting the string literal array undergo array-to-pointer conversion to get a pointer to its first element. So your pointer is pointing at the first element of the string literal array.
但是,请注意,您的第二个示例使用了在 C++03 中已弃用并在 C++11 中删除的功能,允许从字符串文字转换为 char*
.对于有效的 C++11,它必须改为:
However, note that your second example uses a feature that is deprecated in C++03 and removed in C++11 allowing a cast from a string literal to a char*
. For valid C++11, it would have to instead be:
const char* cp = "Hello";
如果确实在 C++03 或 C 中使用到 char*
的转换,则必须确保不要尝试修改字符,否则会出现未定义的行为.
If do use the conversion to char*
in C++03 or in C, you must make sure you don't attempt to modify the characters, otherwise you'll have undefined behaviour.
相关文章