I want to sort an array of structs in C, but using pointer arithmetic. My solution is the following:
#include <stdio.h>
typedef struct{
char* brand;
double cost;
}Car;
void printA(Car * arr, int size);
void sort(Car * arr, int size);
void printA(Car* v,int s){
int i=0;
Car* p;
for (p=&v[0];p<&v[3];p++){
printf("%s %lf \n",p->brand, p->cost);
}
}
void sort(Car* v,int s){
Car *i,*j,*temp,*k;
for (i=&v[0]; i<&v[s]; i++)
{
for (j=&v[0] ; j<&v[s]; j++)
{
k=j+1;
if (j->cost > (j+1)->cost)
{
temp = j;
j = k;
k = temp;
}
}
}
}
int main() {
Car v[3];
Car a = {.brand = "bmw", .cost = 34.56 };
Car b = {.brand = "vw", .cost = 47.35 };
Car c = {.brand = "ford", .cost = 45.23 };
v[0] = a;
v[1] = b;
v[2] = c;
printA(v,3);
sort(v,3);
printA(v,3);
return 0;
}
The issue is that my resulting array does not get sorted. I believe that I should also swap the cost, but I am not entirely sure. What can I try next?
*temp = *j.