So the question I'm working on has me creating a structure with 5 elements: id number, name, department, course, and year. I have to write a function that prints the names of people with certain years and a function that prints all data based on id number input.
When I type in 2020 as an input I get a segmentation fault. What could be causing this?
#include <stdio.h> struct stud { int id; char name[50]; char dep[50]; char course[50]; int year; }; void printbyyear(struct stud *student,size_t sz, int a); void printspecific(struct stud *b,size_t sz, int a); int main() { int yr,num,b; struct stud students[]={ {1,"Jon","math","calc",2019}, {2,"Tim","Language arts","calc",2020}, }; printf("Input year to search for:"); scanf("%d",&yr); printbyyear(students, sizeof(students),yr); printf("Input ID # to search for:"); scanf("%d",&num); printspecific(students, sizeof(students),num); return 0; } void printbyyear(struct stud *b,size_t sz, int a) { int i; for(i=0;i<sz;i++) { if (b[i].year==a) { printf("%d %c %c %c %d",b[i].id,b[i].name,b[i].dep,b[i].course,b[i].year); } } } void printspecific(struct stud *b,size_t sz, int a) { printf("%d %c %c %c %d",b->id,b->name,b->dep,b->course,b->year); return 0; }```
struct studthat you've created areb1andb2. One of those is what you should be passing as the first argument toprintbyyear()---notstruct stud, which is not a variable but the name of a type.printbyyear(struct stud,yr);scanf("%d...", & b[i].id, .... That is, use&b[i].idinstead ofb[i].id. Similarly in other places where appropriate.b[i]at all, then I would expect to see the function signature asvoid printbyyear( struct stud *b....)and the structure's address should be passed.