C ++ const char *和const char []之间的区别 [英] C++ Difference Between const char* and const char[]

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

问题描述

我读了一个关于它们之间的区别的问题:

I read a question on the difference between:

const char*

const char[]

在一段时间内,虽然数组只是指针的语法糖。
但是有些问题困扰着我,我有一段类似于以下内容的代码:

where as for a while, I though arrays were just syntactic sugar for pointers. But something is bugging me, I have a pice of code similar to the following:

namespace SomeNamespace {
    const char* str = { 'b', 'l', 'a', 'h' };
}

我明白了,错误:缩放器对象str需要初始化器中的一个元素。
因此,我尝试了此操作:

I get, error: scaler object 'str' requires one element in initializer. So, I tried this:

namespace SomeNamespace {
    const char str[] = { 'b', 'l', 'a', 'h' };
}

起初,我认为这可能与以下事实有关:当它是const char *时,会应用
的额外操作,而GCC从来都不喜欢在函数外部执行操作(无论如何都是不好的做法),但是错误似乎并不建议这样做。
但是在以下位置:

It worked, at first I thought this may have to do with the fact that an extra operation is applied when it is a const char*, and GCC is never a fan of operations being performed outside a function (which is bad practice anyway), but the error does not seem to suggest so. However in:

void Func() {
    const char* str = { 'b', 'l', 'a', 'h' };
}

它可以按预期编译。没有人知道为什么会这样吗?

It compiles just fine as expected. Does anyone have any idea why this is so?

x86_64 / i686-nacl-gcc 4(.1.4?)Pepper 19工具-链(基本上是GCC)。

x86_64/i686-nacl-gcc 4(.1.4?) pepper 19 tool - chain (basically GCC).

推荐答案

首先,如果您尝试在名称空间范围或函数中使用复合初始化,则没有什么不同:工作!当你写

First off, it doesn't make a difference if you try to use compound initialization at namespace scope or in a function: neither should work! When you write

char const* str = ...;

您获得了指向 char s,例如,可以使用字符串文字初始化。在任何情况下, char 都位于指针之外的其他位置。另一方面,当您写

you got a pointer to a sequence of chars which can, e.g., be initialized with a string literal. In any case, the chars are located somewhere else than the pointer. On the other hand, when you write

char const str[] = ...;

您定义了一个 char s数组。数组的大小由右侧的元素数确定,例如,您的示例 {'b','l','a','h'} 。如果使用了例如 blah ,则其大小当然为5。将数组的元素复制到的位置在这种情况下定义了str

You define an array of chars. The size of the array is determined by the number of elements on the right side and, e.g., becomes 4 your example { 'b', 'l', 'a', 'h' }. If you used, e.g., "blah" instead the size would, of course, be 5. The elements of the array are copied into the location where str is defined in this case.

请注意, char const x [] 在某些情况下可以等同于编写 char const * x :声明函数参数时, char const x [] 实际上与 char const * 相同。

Note that char const x[] can be equivalent to writing char const* x in some contexts: when you declare a function argument, char const x[] actually is the same as char const*.

这篇关于C ++ const char *和const char []之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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