char* and char arr[] Difference - C++/C(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
chararray (whether plainchar,signed char, orunsigned char),char16_tarray,char32_tarray, orwchar_tarray can be initialized by a narrow character literal,char16_tstring literal,char32_tstring 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.
这篇关于char* 和 char arr[] 区别 - C++/C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:char* 和 char arr[] 区别 - C++/C
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
