Hi I'm having trouble sending an array of structures to a function. The structure is set up as below:
struct Leader
{
char surname[15], party[15];
int months_in_power;
};
I then read the data from a file and assign it:
if ((INFILE=(fopen("PM.txt","r"))) == NULL)
{
printf("ERROR: The file could not be opened.");
system("pause");
return 1;
}
while(fscanf(INFILE, "%s %d %d %d %d %s", name,
&start_month, &start_year, &end_month, &end_year, party)>0)
{
struct Leader PM[i];
strcpy(PM[i].surname, name);
strcpy(PM[i].party, party);
months = tenure(start_month, start_year, end_month, end_year);
PM[i].months_in_power = months;
party_time(&PM[i], &Con_months, &Lab_months );
printf("%s: %s, %d months\n", PM[i].surname, PM[i].party, PM[i].months_in_power); //This line all works
i++;
}
Then I try and call my function 'bubble'.
imax=i;
bubble(PM, imax);
and the function bubble is supposed to sort them in order.
void bubble(struct Leader arr[],int max)
{
int j=0, i=0, temp=0;
for (j=1; j<(max);j++)
{
for (i=0; i<(max-1); i++)
{
if (arr[i].months_in_power < arr[i+1].months_in_power)
{
temp = arr[i].months_in_power;
arr[i].months_in_power=arr[i+1].months_in_power;
arr[i+1].months_in_power = temp;
}
else continue;
}
}
for( i=0; i<max; i++)
{printf("%d\n", arr[i].months_in_power);}
return ;
}
If I try and print arr[i].months_in_power during the sorting loops it just prints rubbish and crashes. Whats wrong?
EDIT: The PM.txt file contains information like:
Attlee 7 1945 10 1951 Labour
Churchill 11 1951 5 1955 Conservative
Eden 6 1955 12 1956 Conservative
etc etc...
Thanks
PM.txtthat will help us understand where array overflow may be occurring, if at all.tenure()(which looks like it calculates months during tenure?)