I am trying to perform the bulk of the work intended by calling the swap function. The point of the program is to initialize the week array in the main function, then use the swap function to sort the structure member 'temp' of the array, from least to greatest. The end result should sort the array values for temp from least to greatest (and keep the day names with the corresponding temp).
Ive already tried a variety of syntax (incorrectly) and am not sure what I am doing wrong. I am trying to learn the proper way to access structure members as pointers and manipulate them with external functions.
struct weather {
char day[10];
float temp;
};
void swap (struct weather *p);
int main()
{
struct weather week[7] = {
{ "Sunday", 72.5 },
{ "Monday", 68.4 },
{ "Tuesday", 75.0 },
{ "Wednesday", 73.8 },
{ "Thursday", 65.1 },
{ "Friday", 72.8 },
{"Saturday", 75.2 }
};
swap(week);
int x;
puts("This week's forecast from coldest to warmest:");
for(x=0;x<7;x++)
printf("%10s %.1f degrees\n",
week[x].day,
week[x].temp);
return(0);
}
void swap (struct weather *p){
int x;
int t;
for (x=0;x<7;x++){
if (p[x+1].temp < p[x].temp){
t = p[x+1].temp;
p[x+1].temp = p[x].temp;
p[x].temp = t;
}
}
}
I would expect the second member array (temp) of the structure to be in ascending order. It is not, and Saturday is listed with a temp of 0. The intent of my question is to ensure I am manipulating the values of the array in memory properly.
struct weather t = p[x+1]; p[x+1] = p[x]; p[x] = t;? Otherwise, you end up changing the day associated with each temperature, in general. I've not reviewed for other problems — it looks like you may not have enough loops in yourswap()function, which should perhaps be renamedsort().t = p[x+1].temp;What values willx+1reach in your code? What is maximum index ofp?