【问题标题】:How to properly initialize a const int const * variable?如何正确初始化 const int const * 变量?
【发布时间】:2016-08-14 10:57:27
【问题描述】:

所以我有一个struct

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

我有一个const 数组int

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

现在我有一个myStruct_sconst 数组,使用指定的初始化程序进行了初始化:

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
            },
        //...
}

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

感谢您的帮助:)。

【问题讨论】:

  • array_ptr = &constArray[0];
  • 数组索引从 0 开始。您的作业 ([1] = 1) 从 1 开始。与问题无关,但看起来很可疑。
  • @davmac:你是对的!实际上我使用enum 作为索引来填充数组。我从不使用幻数:)。我的代码简化得太快了!

标签: c arrays pointers initialization constants


【解决方案1】:

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

【讨论】:

  • 正确,但可以解释为什么 &constArray 不起作用。
  • 啊,好吧,我会试试,但我的英语很差:)
  • @Plouff:不客气,您可以在comp.lang.c FAQ list · Question 6.13找到更多详细信息
  • @AlterMann:再次感谢 C 常见问题解答链接 :)。
【解决方案2】:

您应该删除 constArray 之前的 & 符号,这将产生一个兼容的指针类型。

原因:数组的处理方式与 C 中的指针类似。所以constArray 已经有效地成为const int *const。但是当你获取地址时,即&constArray,你实际上得到了一个与const int *const *const兼容的类型。

【讨论】:

  • 没有。您将获得与const int (*) [] 兼容的类型。当数组是& 的操作数时,数组不会衰减为指针。
  • 第二段是垃圾
猜你喜欢
  • 1970-01-01
  • 2019-09-02
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 2014-09-08
  • 2021-10-19
相关资源
最近更新 更多