简体   繁体   中英

Using a constant-length 2D array as a struct member in C

I'm trying to do the following in C:

  • create a 2d array (with compile-time known dimensions) of integers on the stack
  • assign the array as a member of a struct (which used in a callback function elsewhere)

I tried using a struct either with a 2d array member or pointer to 2d array - see code below.

I could probably just use a double pointer allocated with malloc and have a double pointer struct member, but I was trying to avoid dynamic allocation (and I'd like to understand what is going wrong). I also don't want to copy the array because the callback function might mutate the data.

#include <stdio.h>

struct numbers_struct {
    int numbers[2][3];
};

struct pointer_to_numbers_struct {
    int (*numbers)[2][3];
}

int main() {
    int numbers[2][3] = { {1,2,3},{4,5,6} };

    /* try to use struct with 2d array member
     * error: array type `int[2][3]` not assignable */
    struct numbers_struct num_struct;
    num_struct.numbers = numbers;

    /* try to use struct with pointer to 2d array member 
     * contains random/invalid data */
    struct pointer_to_numbers_struct ptr_num_struct;
    ptr_num_struct.numbers = &numbers;
}


You cannot assign an array like that, try memcpy instead:

memcpy(num_struct.numbers, numbers, sizeof numbers);

You could initialize the arrays within the initializer of struct numbers_struct .

struct numbers_struct num_struct = { { {1,2,3},{4,5,6} } };
struct pointer_to_numbers_struct ptr_num_struct = { &num_struct.numbers };

If you want the structure to be persistent, add static to its definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM