string array initialisation

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 12:53:14

问题


This is a continuation of another question I have.

Consider the following code:

char *hi = "hello";

char *array1[3] = 
{
    hi,
    "world",
    "there."
};

It doesn't compile to my surprise (apparently I don't know C syntax as well as I thought) and generates the following error:

  error: initializer element is not constant

If I change the char* into char[] it compiles fine:

char hi[] = "hello";

char *array1[3] = 
{
    hi,
    "world",
    "there."
};

Can somebody explain to me why?


回答1:


In the first example (char *hi = "hello";), you are creating a non-const pointer which is initialized to point to the static const string "hello". This pointer could, in theory, point at anything you like.

In the second example (char hi[] = "hello";) you are specifically defining an array, not a pointer, so the address it references is non-modifiable. Note that an array can be thought of as a non-modifiable pointer to a specific block of memory.

Your first example actually compiles without issue in C++ (my compiler, at least).



来源:https://stackoverflow.com/questions/7834643/string-array-initialisation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!