lan*_*ng2 10 c string pointers ansi-c
这是我的另一个问题的延续.
请考虑以下代码:
char *hi = "hello";
char *array1[3] =
{
hi,
"world",
"there."
};
Run Code Online (Sandbox Code Playgroud)
它没有编译到我的意外(显然我不知道C语法以及我认为)并生成以下错误:
error: initializer element is not constant
Run Code Online (Sandbox Code Playgroud)
如果我将char*更改为char [],则编译正常:
char hi[] = "hello";
char *array1[3] =
{
hi,
"world",
"there."
};
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释原因吗?
在第一个示例(char *hi = "hello";)中,您将创建一个非const指针,该指针初始化为指向静态const字符串"hello".从理论上讲,这个指针可以指向你喜欢的任何东西.
在第二个示例(char hi[] = "hello";)中,您专门定义了一个数组,而不是一个指针,因此它引用的地址是不可修改的.请注意,可以将数组视为指向特定内存块的不可修改指针.
您的第一个示例实际上在C++中编译没有问题(至少我的编译器).