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

Plo*_*uff 8 c arrays pointers initialization const

所以我有一个struct:

typedef struct myStruct
{
    const int *const array_ptr;
} myStruct_s;
Run Code Online (Sandbox Code Playgroud)

我有一个const数组int:

const int constArray[SIZE1] =
{
        [0] = 0,
        [1] = 1,
        [2] = 2,
        //...
};
Run Code Online (Sandbox Code Playgroud)

现在我有一个使用指定的初始化器初始化的const数组myStruct_s:

const myStruct_s structArray[SIZE2] =
{
        [0] =
            {
                    .array_ptr = &constArray
            },
        //...
}
Run Code Online (Sandbox Code Playgroud)

我收到警告:

类型为"const int(*)[SIZE1]"的值不能用于初始化"const int*const"类型的实体

如何正确初始化此指针?

我想避免:

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

如果可能的话,因为我觉得我告诉编译器"我不知道我在做什么,请不要检查类型"...

谢谢你的帮助 :).

Dav*_*eri 11

constArray 已经(衰变成)指针,你想要的

.array_ptr = constArray
Run Code Online (Sandbox Code Playgroud)

要么

.array_ptr = &constArray[0] /* pointer to the first element */
Run Code Online (Sandbox Code Playgroud)

代替

.array_ptr = &constArray /* you don't want the address of */
Run Code Online (Sandbox Code Playgroud)

考虑

int a[] = {1,2};
int *p = &a;
Run Code Online (Sandbox Code Playgroud)

这是不正确的,因为p想要指向int(&a[0]或简单a)的指针,而不是指向2 int(&a)数组的指针