所以我有struct
:
typedef struct myStruct
{
const int *const array_ptr;
} myStruct_s;
我有一个const
int
数组:
const int constArray[SIZE1] =
{
[0] = 0,
[1] = 1,
[2] = 2,
//...
};
现在我使用指定的初个化程序初始化了const
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
},
//...
}
如果可能,因为我觉得我告诉编译器“我不知道我在做什么,请不要检查类型”...
感谢您的帮助:)。
答案 0 :(得分: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 {{1}的数组的指针}(int
)
答案 1 :(得分:-1)
你应该从constArray之前删除&符号,然后产生兼容的指针类型。
原因:数组的处理方式与C中的指针类似。因此constArray
已经有效const int *const
。但是当你拿到地址时,即&constArray
你实际上得到的类型与const int *const *const
兼容。