简体   繁体   English

C ++在const char *和const char []之间的区别

[英]C++ Difference Between const char* and const char[]

I read a question on the difference between: 我读了一个关于以下区别的问题:

const char*

and

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' };
}

I get, error: scaler object 'str' requires one element in initializer. 我得到,错误:缩放器对象'str'在初始化器中需要一个元素。 So, I tried this: 所以,我试过这个:

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

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. 它起作用,起初我认为这可能与以下事实有关:当它是一个const char *时应用额外的操作,并且GCC从不是在函数外执行的操作的粉丝(这无论如何都是不好的做法),但错误似乎并不是这样。 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 tool - chain (basically GCC). x86_64 / i686-nacl-gcc 4(.1.4?)pepper 19工具 - 链(基本上是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 = ...;

you got a pointer to a sequence of char s which can, eg, be initialized with a string literal. 你有一个指向char序列的指针,例如,可以用字符串文字初始化。 In any case, the char s are located somewhere else than the pointer. 在任何情况下, char都位于除指针之外的其他位置。 On the other hand, when you write 另一方面,当你写作

char const str[] = ...;

You define an array of char s. 您定义了一个char数组。 The size of the array is determined by the number of elements on the right side and, eg, becomes 4 your example { 'b', 'l', 'a', 'h' } . 数组的大小由右侧元素的数量决定,例如,变为4你的例子{ 'b', 'l', 'a', 'h' } If you used, eg, "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. 如果你使用了例如"blah"那么大小当然是5.数组的元素被复制到在这种情况下定义str的位置。

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* . 请注意, char const x[] 可以等效于在某些上下文中编写char const* x :当声明一个函数参数时, char const x[]实际上与char const*相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM