Reputation: 143
I'm trying to do the following in C:
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;
}
Upvotes: 0
Views: 49
Reputation: 14157
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.
Upvotes: 0
Reputation: 11377
You cannot assign an array like that, try memcpy instead:
memcpy(num_struct.numbers, numbers, sizeof numbers);
Upvotes: 1