0

I am trying to make an Array of struct pointers so I can terminate the end of the array with null and be able to run through the array of structs.

I originally got an array of structs working but when changing the array of structs into an array of struct pointers I get a segmentation fault when trying to assign or access values of the structs by dereferencing.

I like to know what I am doing wrong.

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

typedef struct s{
    int a;
    char *b;
    int c;
    int d;
}s;

s** readStruct(){
    FILE *f = fopen("file.csv", "r");
    if(!f){
        printf("Can't open file\n");
        exit(1);
    }

    //An array of struct pointers of size 50
    s **x = (s **)malloc(50 * sizeof(s *));
    char str[60];
    int i = 0;

    //Loop through each line of the file while !EOF
    //copy each line to string for tokenizing
    while(fgets(str, 60, f)){

        char *tok = strtok(str, ",/n");
        // segmentation fault happens here:
        x[i]->a = atoi(tok);
        // also happens here too:
        printf("%d\n", x[i]->a);

        tok = strtok(NULL, tok);
        // segmentation fault would result here:
        strcpy(x[i]->b, tok);

        tok = strtok(NULL, ",\n");
        // and here:
        x[i]->c = atoi(tok);

        tok = strtok(NULL, ",\n");
        // and here:
        x[i]->d = atoi(tok);

        i++;
    }

    return x;
}

int void main(){

    s **x = readStruct();

    for(int i = 0; (x + i) < NULL; i++){
        printf("%d\n", x[idx]->a);
        printf("%s\n", x[idx]->b);
        printf("%d\n", x[idx]->c);
        printf("%d\n", x[idx]->d);
        printf("\n");
    }


    return 0;
}
1
  • This worked, makes sense too. Commented Nov 6, 2015 at 22:47

1 Answer 1

1

You allocated the space for the array, but not for each individual struct that the pointers in the array point to:

while(fgets(str, 60, f)){

    char *tok = strtok(str, ",/n");

    a[i] = malloc( sizeof( s ) );
    //...

Other notes:

  • In C, you should not cast the result of malloc().
  • Since you are reusing the delimiter string, it would be good to store that in a variable (const char* delim = ",\n") instead of retyping the same sequence. It helps to prevent errors, like typing ",/n", when you mean ",\n" which you did.
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that did that job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.