字符串数组初始化

字符串数组初始化

本文介绍了字符串数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是另一个我有一个延续。

This is a continuation of another question I have.

考虑以下code:

char *hi = "hello";

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

这并不编译令我惊讶(显然我不知道C语法以及我认为),并生成以下错误:

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

如果我改变的char *成char []它编译罚款:

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?

推荐答案

在第一个例子中(的char * HI =你好; ),要创建一个非-const指针,初始化为指向静态常量字符串hello。该指针在理论上,点你喜欢的东西。

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.

您第一个例子中实际上没有问题,在编译C ++(我的编译器,至少)。

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

这篇关于字符串数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:14