-1

How can one define and use a dynamically allocated array, whose members are static const?

Background: I need to do the above, to store the several transaction that are requested at runtime. The snipet bellow exemplifies how to define a transaction. This code uses the 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));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
AmiguelS
  • 805
  • 2
  • 10
  • 28

2 Answers2

2

How can one define and use a dynamically allocated array, whose members are static const?

You can't. The members of an array necessarily have the same storage class and linkage as the array itself, therefore a dynamically-allocated array cannot have static members. Such an array can, however, have copies of or pointers to objects with static storage class and/or linkage.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

You cannot statically initialize members of a dynamically allocated array: the only two options supplied by the standard library are uninitialized, i.e. malloc, and zero-initialized, i.e. calloc.

If you would like to initialize elements of your array to anything else, you need to perform assignments yourself. C lets you assign structs directly, so initializing an array of structs is not much different from initializing an array of primitives.

Here is a small example:

// 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;
}

What looks like regular assignments above, e.g. d[0] = data[1], performs a copy of the content of statically initialized data[1] into dynamically initialized d[0].

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523