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

2019-05-07 23:17发布

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. 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. 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).

1条回答
Ridiculous、
2楼-- · 2019-05-07 23:37

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 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[] = ...;

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.

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*.

查看更多
登录 后发表回答