的char *和char ARR []差 - C ++ / C [英] char* and char arr[] Difference - C++/C

查看:181
本文介绍了的char *和char ARR []差 - C ++ / C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在刚刚从C开始走出++,我想知道,如果有人可以解释一下。

Just starting out in C++, I was wondering if someone could explain something.

我相信你可以初始化通过以下方式字符数组

I believe you can initialise a char array in the following way

 char arr[] = "Hello"

这将创建一个字符数组,其值'H','E','L','L','O','\\ 0'

This will create a Char array with the values 'H', 'e', 'l', 'l', 'o', '\0'.

但是,如果我这样做创建这个:

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?

推荐答案

该字符串文字本身有数组类型。因此,在你给第一个例子,有实际参与两个数组。第一个是包含字符串数组,第二个是,你声明数组改编。从字符串中的字符复制到改编。在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:

A 字符阵列(无论是纯字符符号字符 unsigned char型), char16_t 阵列, char32_t 阵列,或 wchar_t的阵列可以通过一个狭窄的字符文字进行初始化, char16_t 字符串, char32_t 字符串文字或宽字符串文字,分别或适当类型的字符串大括号括起来。该字符串的值连续的字符初始化数组中的元素。

A char array (whether plain char, signed char, or unsigned char), char16_t array, char32_t array, or wchar_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.

但是,请注意你的第二个示例使用一个特点,就是去precated在C ++ 03并删除在C ++ 11允许从字符串文字到字符铸* 。对于有效的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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