【问题标题】:Dynamically allocated array with static const members具有静态 const 成员的动态分配数组
【发布时间】:2016-06-27 02:08:37
【问题描述】:

如何定义和使用一个动态分配的数组,其成员为static const

背景:我需要执行上述操作,以存储运行时请求的几个事务。下面的代码片段举例说明了如何定义事务。此代码使用 Nordic Semiicondictor nRF5x SDK。

static app_twi_transfer_t const transfers[] =
{
    APP_TWI_WRITE(MMA7660_ADDR, p_reg_addr, 1, APP_TWI_NO_STOP), 
    APP_TWI_READ (MMA7660_ADDR, p_buffer,   byte_cnt, 0)
};

static app_twi_transaction_t const transaction =
{
    .callback            = read_mma7660_registers_cb,
    .p_user_data         = NULL,
    .p_transfers         = transfers,
    .number_of_transfers = sizeof(transfers)/sizeof(transfers[0])
};

APP_ERROR_CHECK(app_twi_schedule(&m_app_twi, &transaction));

【问题讨论】:

  • 您的帖子中没有static const 成员,app_twi_transaction_t 结构中也没有。
  • 帖子中也没有动态分配的数组!
  • @LPs 那么什么是'static app_twi_transaction_t const transaction'?
  • 并且没有数组,因为问题是如何在代码 sn-p 上定义类型数组!
  • @AmigueIS 变量...?

标签: c arrays dynamic static nrf51


【解决方案1】:

如何定义和使用一个动态分配的数组,它的成员是静态常量?

你不能。数组的成员必须与数组本身具有相同的存储类和链接,因此动态分配的数组不能具有静态成员。但是,这样的数组可以有 副本指向 具有静态存储类和/或链接的对象的指针。

【讨论】:

    【解决方案2】:

    您不能静态初始化动态分配的数组的成员:标准库提供的唯一两个选项是未初始化,即malloc零初始化,即calloc

    如果您想将数组的元素初始化为其他任何内容,您需要自己执行分配。 C 允许您直接分配 structs,因此初始化 structs 数组与初始化基元数组没有太大区别。

    这是一个小例子:

    // This is your struct type
    typedef struct {
        int a;
        int b;
        int c;
    } test_t;
    // This is some statically initialized data
    test_t data[] = {
        {.a=1, .b=2, .c=3}
    ,   {.a=10, .b=20, .c=30}
    ,   {.a=100, .b=200, .c=300}
    };
    int main(void) {
        // Allocate two test_t structs
        test_t *d = malloc(sizeof(test_t)*2);
        // Copy some data into them:
        d[0] = data[1];
        d[1] = data[2];
        // Make sure that all the data gets copied
        printf("%d %d %d\n", d[0].a, d[0].b, d[0].c);
        printf("%d %d %d\n", d[1].a, d[1].b, d[1].c);
        free(d);
        return 0;
    }
    

    上面看起来像常规作业的内容,例如d[0] = data[1],将静态初始化的data[1]的内容复制到动态初始化的d[0]中。

    Demo.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 2013-04-13
      • 2013-02-05
      • 2020-07-04
      • 1970-01-01
      相关资源
      最近更新 更多