初始化指针数组的指针 [英] Initializing an array of pointers to pointers

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

问题描述

这个例子正常工作:

static char *daytab[] = {
    "hello",
    "world"
};

这不:

static char *daytab[] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

我看到它的方式是,第一个示例创建一个充满指向两个字符串(这本身是数组)的数组。第二个例子,海事组织,应该是相同的 - 创建一个数组和指针的两个字符数组填充

The way I see it is that the first example creates an array that is filled with pointers to the two string literals (which themselves are arrays). The second example, IMO, should be identical - create an array and fill it with pointers to the two char arrays.

能否为什么第二个例子是错误的有人向我解释?

Could someone explain to me why the second example is wrong?

P.S。你也许可以写出像这样(没有测试过):

P.S. You could probably write it like this (haven't tested it):

static char a[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static char b[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static char *daytab[] = {
    a,
    b
};

但是,看起来像太多的工作。)

But that looks like too much work :).

推荐答案

{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

只是一个数组初始化。它本身不建立一个数组。第一个例子,当你分配一个字符串的指针,确实创造了在静态存储(隐藏你)这些字符串,然后刚分配指针给他们。

Is just an array initializer. It doesn't itself create an array. The first example, when you assigned a string literal to a pointer, DID create those strings in static storage (hidden to you), and then just assigned the pointers to them.

因此​​,基本上,是没有办法来初始化字符*与数组初始化。您需要创建一个实际的数组,并分配这些数字给它。你将不得不做这样的事情:

So basically, there is no way to initialize your char* with the array initializer. You need to create an actual array, and assign those numbers to it. You would have to do something like:

char a[][] = { {32, 30, 0}, {34, 32, 33, 0} }; // illegal

但是,这是非法的。

But that is illegal.

您需要单独建立阵列,并将它们分配到像你的最后一个例子阵列。

You need to build the array separately and assign them into an array like your last example.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆