How do I assign fixed size two dimensional arrays in a structure?

I have a structure 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 would like to:

my_struct * thing = (my_struct *)malloc(sizeof(my_struct));

      

But when I do this and then try to access anything in the vectors, I get a seg error.

If I instead declare vectors in a struct as:

typedef struct _my_struct {
    float **first_vector;
    float **second_vector;
    int some_val;
} my_struct;

      

and then highlight:

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 the first and second vectors are fixed in size and known at compile time, it seems odd that I should individually allocate memory for them. Is there a way to declare them in a struct so that I can just malloc the new struct without allocating memory for each vector separately?

+3


source to share


1 answer


What you should be fine. Aside from the funky typedef in the top and odd declaration, my_struct * struct = malloc...

this little test case works for me:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    float first[10][20];
    float second[10][20];
    int val;
} my_struct;

int main(void) {
    printf("Sizeof mystruct %d\n", sizeof(my_struct));

    my_struct* str = malloc(sizeof(my_struct));
    if(!str) {
        printf("Memory allocation error!");
        exit(1);
    }

    str->first[0][0] = 1;
    str->second[1][19] = 15;

    printf("values %f %f\n", str->first[0][0], str->second[1][19]);

    free(str);

    return 0;

}

      

Output:



Sizeof mystruct 1604
values 1.000000 15.000000

      

Also, you don't have to supply the return value from malloc. It can hide important compiler warnings.

+3


source







All Articles