-4
typedef struct
{
    char nazwisko[30];
    double srednia;
    int semestr;
}osoba;

void WyszukiwanieSemestr(osoba *stud, int sem, int i)
{
    int a;
    printf("\n");
    for(a=0;a<i;++a)
    {
       if(stud[a].semestr == sem)
       {
          printf("%d. %s %.3lf %d\n",a+1,stud[a].nazwisko,stud[a].srednia,stud[a].semestr);
       }
    }
    printf("\n");
}

And in int main():

osoba *os;
os = (osoba*) malloc(M*sizeof(osoba));
int sem, i = 5;
scanf("%d",sem);
WyszukiwanieSemestr(os,sem,i);

When I try to compare stud[a].semestr == sem in the function, my program crashes. What is the problem? How can I solve this?

4

2 回答 2

1

The primary problem is likely your scanf. You need to pass the ADDRESS of sem. Instead, this is copying your keyboard input into a random memory location.

scanf("%d", &sem);

Also,

You're allocating M osoba objects for os, but you're passing in a size of 5 to WyszukiwanieSemestr. You should pass in M instead.

If M is smaller than 5, you will run off the end of your array in your for loop inside WyszukiwanieSemestr

WyszukiwanieSemestr(os, sem, M);

Also, there's no need to cast the response from malloc.

于 2013-05-26T22:09:49.543 回答
1
scanf("%d",sem);

should be

scanf("%d", &sem);
于 2013-05-26T22:12:50.773 回答