0

I'm trying to make an array of structs by using malloc to allocate the memory needed like so:

typedef struct stud{
   char stud_id[MAX_STR_LEN];
   char stud_name[MAX_STR_LEN];
   Grade* grd_list;
   Income* inc_list;
}Stud;

Stud* students = malloc(sizeof(Stud)*STUDENT_SIZE);

The problem is that I have a function that adds id and name to a place in the array like so:

void new_student(Stud* students[], int stud_loc){
   scanf("%s", students[stud_loc]->stud_id);
   printf("%s", students[stud_loc]->stud_id);
   scanf("%s", students[stud_loc]->stud_name);
   printf("%s", students[stud_loc]->stud_name); 
}

But after the first call to the function, which works, the second one gives me the error:

Segmentation fault (core dumped)

And I can only think that it must mean I'm not doing this right and all the memory is probably going into one place and not in an array form. I'd rather do

  Stud students[STUDENT_SIZE];

but in this case I must use malloc.

I tried using calloc but I still get the same error.

4
  • Did you (not) check the return value of malloc()? Commented Dec 14, 2016 at 17:44
  • 1
    Please create a minimal reproducible example that demonstrates the problem. I'd like to see how you passed a Stud* value to a function that takes Stud*[]. Commented Dec 14, 2016 at 17:50
  • new_student(Stud* students[], ... is equal to new_student(Stud** students, .... But you want new_student(Stud* students,.... The compiler should have warned you about this. Commented Dec 14, 2016 at 17:58
  • Ok i must have misunderstood you, but your answer seem to solve something im testing it right now. Commented Dec 14, 2016 at 17:58

1 Answer 1

4

There's a mismatch between the local variable Stud *students and the function parameter Stud *students[]. Those two variables ought to have the same type.

The local variable and malloc() look good. new_student has an undesirable extra layer of pointers. It should look like this instead:

void new_student(Stud* students, int stud_loc){
   scanf ("%s", students[stud_loc].stud_id);
   printf("%s", students[stud_loc].stud_id);
   scanf ("%s", students[stud_loc].stud_name);
   printf("%s", students[stud_loc].stud_name); 
}

You would then call it like so:

Stud* students = malloc(sizeof(Stud)*STUDENT_SIZE);

new_student(students, 0);
new_student(students, 1);
new_student(students, 2);
Sign up to request clarification or add additional context in comments.

Comments

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.