I have a struct that looks like this:
typedef struct _my_struct {
float first_vector[SOME_NUM][OTHER_NUM];
float second_vector[SOME_NUM][OTHER_NUM];
int some_val;
} my_struct;
I’d like to do:
my_struct * thing = (my_struct *)malloc(sizeof(my_struct));
But when I do so and then try to access anything in the vectors, I get a seg fault.
If I instead declare the vectors in the struct as:
typedef struct _my_struct {
float **first_vector;
float **second_vector;
int some_val;
} my_struct;
and then allocate with:
my_struct->first_vector = (float**)malloc(sizeof(float*) * SOME_NUM);
my_struct->second_vector = (float**)malloc(sizeof(float*) * SOME_NUM);
int i;
for (i = 0; i < SOME_NUM; i++){
my_struct->first_vector[i] = (float*)malloc(sizeof(float) * OTHER_NUM);
my_struct->second_vector[i] = (float*)malloc(sizeof(float) * OTHER_NUM);
}
Then everything works fine.
Since first and second vector are fixed in size and known at compile time, it seems strange that I have to individually allocate memory for them. Is there a way to declare them in the struct so that I can just malloc a new struct without also allocating memory for each vector separately?
What you have should be fine.. aside from the funky typedef at the top and odd declaration of
my_struct * struct = malloc...this small test case works for me:Output is:
Additionally, you should not cast the return value of malloc. It can hide important compiler warnings.