Seg fault when trying to init an array of structs

Viewed 59

I am just trying to initialize an array of structs using a separate function in c but when i call the function it causes the program to crash due to seg fault.

All i want to do is initialize the value and set the pos = to k+1 using a loop of the size n a constant of 20 can anyone help, perhaps their is something which is i am completely missing thanks.

Code:

  #include <stdio.h>
    #define n 20
    
    typedef struct history {
        char* value;
        int pos;
    } hist;

hist* history_struct[n];

void init_struct() {
    /* this function will create an array of structs of size 20*/
    for (int k = 0; k < n; k++) {
        history_struct[k]->value = (hist*) malloc(sizeof(hist*));
        history_struct[k]->pos = k+1;
        printf("indexes = %d ", history_struct[k]->pos);
    }
    
}
1 Answers

I believe you have declared an array of pointers to structs, simple clean up of the code will sort you out from the null pointer you seem to be having. You also use malloc in a weird way if value is just a char* then just take the sizeof(char*) and there is no need to cast

hist history_struct[n];

    void init_struct() {
        /* this function will create an array of structs of size 20*/
        for (int k = 0; k < n; k++) {
            history_struct[k].value = malloc(sizeof(char*));
            history_struct[k].pos = k+1;
            printf("indexes = %d ", history_struct[k].pos);
        }
        
    }

so we remove the pointer then meaning we got back to the dot notation instead of "->" as we are no longer using a pointer hope this helped and sorted out your issue any further questions just ask me

Related