字符串数组初始化
这是我的另一个问题的延续。
考虑以下代码:
char *hi = "hello";
char *array1[3] =
{
hi,
"world",
"there."
};
它的编译结果出乎我的意料(显然我并不像我想象的那样了解 C 语法)并生成以下错误:
error: initializer element is not constant
如果我将 char* 更改为 char[],它编译得很好:
char hi[] = "hello";
char *array1[3] =
{
hi,
"world",
"there."
};
有人可以吗向我解释一下为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第一个示例 (
char *hi = "hello";
) 中,您将创建一个非常量指针,该指针被初始化为指向静态常量字符串“hello”。理论上,这个指针可以指向任何你喜欢的东西。在第二个示例 (
char hi[] = "hello";
) 中,您专门定义了一个数组,而不是指针,因此它引用的地址是不可修改的。请注意,数组可以被视为指向特定内存块的不可修改的指针。您的第一个示例实际上在 C++ 中编译没有问题(至少是我的编译器)。
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).