yer*_*syl 6 c struct pointers bubble-sort
我想使用冒泡排序算法和C中的指针对结构数组进行排序.我有一个汽车结构:
typedef struct{
    char model[30];
    int hp;
    int price;
}cars;
我为12个项目分配内存:
cars *pointer = (cars*)malloc(12*sizeof(cars));
并从文件中读取数据:
for (i = 0; i <number ; i++) {
    fscanf(file, "%s %i %i\n", (pointer+i)->model, &(pointer+i)->hp, &(pointer+i)->price);
}
我将指针传递ptr给bubbleSort函数:
bubbleSort(pointer, number);
这是我的bubbleSort功能:
void bubbleSort(cars *x, int size) {
    int i, j;
    for (i=0;i<size-1;i++) {
    int swapped = 0;
    for (j = 0; j < size - 1 - i; j++) {
        if ( (x+i)->hp > (x+j+1)->hp ) {
            cars *temp = (x+j+1);
            x[j+1] = x[j];
            x[j] = *temp;
            swapped = 1;
        }
    }
        if (!swapped) {
        //return;
        }
    }
}
问题是我不知道如何使用指针交换项目.
考虑以下用于排序功能的解决方案:
void bubbleSort(cars *x, int size) 
{
    int i, j;
    for (i = 0; i < size-1; i++) 
    {
        for (j = 0; j < size-1-i; j++) 
        {
            if ( x[j].hp > x[j+1].hp ) 
            {
               cars temp = x[j+1];
               x[j+1] = x[j];
               x[j] = temp;
            }
        }
    }
}
问题出在数据交换部分