静态char*的数组

Ema*_*llo 1 c c++ arrays

我想知道C++是否正确:

static char *arrayExample[]  = 
{
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h"
};
Run Code Online (Sandbox Code Playgroud)

Bal*_*arq 5

我想知道在C++中是否写得正确

static char *arrayExample[]  = 
{
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h"
};
Run Code Online (Sandbox Code Playgroud)

即使你不添加const修饰符,它是否编译?是的,但这是误导.字符串文字存储在内存区域中,源代码的所有字符串文字都是一个接一个地保存的.这意味着你不应该搞乱它(在PC中它不会发生.但它可以映射到ROM内存).

所以,它基本上是正确的.但是,这个文字数组并不意味着要修改,所以你应该更好地重写它:

static const char *arrayExample[]  = 
{
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h"
};
Run Code Online (Sandbox Code Playgroud)

您已将其声明为static:这意味着它只能在其自己的翻译单元中显示(即创建它的非常cpp文件).如果这是你的意图(你不打算能够在翻译单位之间分享),那就完全可以了.

希望这可以帮助.