如何正确地初始化一个const int const *变量?

8

我有一个struct

typedef struct myStruct
{
    const int *const array_ptr;
} myStruct_s;

我有一个constint数组:

const int constArray[SIZE1] =
{
        [0] = 0,
        [1] = 1,
        [2] = 2,
        //...
};

现在我有一个使用指定初始化器初始化的myStruct_s常量数组:
const myStruct_s structArray[SIZE2] =
{
        [0] =
            {
                    .array_ptr = &constArray
            },
        //...
}

我收到了以下警告:

无法使用类型为“const int (*)[SIZE1]”的值来初始化类型为“const int *const”的实体

我该如何正确初始化这个指针?

我想避免以下情况:

const myStruct_s structArray[SIZE2] =
{
        [0] =
            {
                    .array_ptr = (const int *const) &constArray
            },
        //...
}

如果可能的话,因为我感觉我在告诉编译器:“我不知道我在做什么,请不要检查类型”……谢谢你的帮助 :)。

1
array_ptr = &constArray[0]; - Nadir
3
数组索引从0开始。你的赋值操作([1] = 1)从1开始。虽然不涉及问题,但看起来有点可疑。 - davmac
@davmac:你说得对!实际上我使用enum作为索引来填充数组。我从不使用魔法数字 :)。我有点过于快速地简化了我的代码! - Plouff
1个回答

11
constArray已经(衰变为)指针,您想要的是
.array_ptr = constArray

或者

.array_ptr = &constArray[0] /* pointer to the first element */

替代

.array_ptr = &constArray /* you don't want the address of */

考虑以下内容:
int a[] = {1,2};
int *p = &a;

这是不正确的,因为p需要一个指向int类型的指针(&a[0]或者简单地写成a),而不是一个指向包含2个int类型的数组的指针(&a


1
正确,但需要解释为什么&constArray不起作用。 - davmac
啊,好的,我会尝试,但我的英语很差 :) - David Ranieri
1
@Plouff:不客气,你可以在comp.lang.c FAQ list · Question 6.13找到更多详细信息。 - David Ranieri
1
@AlterMann:再次感谢您提供的C语言FAQ链接 :)。 - Plouff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接