【发布时间】:2015-06-21 23:58:21
【问题描述】:
我想使用 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;
}
}
}
问题是我不知道如何使用指针交换项目。
【问题讨论】:
-
试试
cars *temp = (x+j+1);改成cars temp = x[j+1];..x[j] = temp; -
还有
if ( (x+i)->hp > (x+j+1)->hp ) {-->if ( (x+j)->hp > (x+j+1)->hp ) { -
永远不需要键入 malloc 的返回值。那是 C++ 的事情。只需使用
cars *pointer = malloc(12*sizeof(cars));
标签: c pointers struct bubble-sort