我在快速排序方面遇到问题。它应该按作者姓名对书籍进行排序。这是代码
#include <stdio.h>
#include <stdlib.h>
struct book {
char title[80];
char autor[80];
int pages;
};
int comparator (const void * a, const void *b)
{
struct book * ia=(struct book*)a;
struct book * ib=(struct book*)b;
return (strcmp(ia->autor,ib->autor));
}
int main(int argc, char ** argv)
{
int c = 2;
int i;
//Pointer to array of struct pointers, malloc for 2 structs
struct book **ptr = (struct book*)malloc(c*sizeof(struct book));
for(i=0;i<c;i++) {
//malloc for every struct
//also, if I'm doing it right?
ptr[i] = (struct book*)malloc(sizeof(struct book));
printf("Title: ");
scanf("%s",ptr[i]->title);
printf("Autor: ");
scanf("%s",ptr[i]->autor);
}
for(i=0;i<c;i++) {
printf("Before Quick sort Autor: %s, Title: %s \n",ptr[i]->autor,ptr[i]->title);
}
qsort(ptr,2, sizeof(struct book), comparator);
printf("QSORT DONe...\n\n");
for(i=0;i<c;i++) {
printf("TEST");
printf("After quick sort: Autor: %s, Title: %s \n",ptr[i]->autor,ptr[i]->title);
}
return 0;
}
因此程序可以编译,但仅到达 printf("TEST");
(TEST 在屏幕上打印),然后崩溃。
我用快速排序破坏了我的数组吗?或者会发生什么?
您还可以检查一下我的代码是否可以吗?尤其是 mallocs
在我的代码中(实际上)做了什么,因为我不确定我是否正确使用了它们。
谢谢!
最佳答案
存在一些小问题和困惑:
1) 您失踪了#include <string.h>
对于 strcmp
2)您正在分配一个指针数组,这可能不是您想要做的。 C 中的数组是指向数组第一个元素的指针,因此如果您使用 (struct book*) malloc(n * sizeof(struct book))
进行分配您已经分配了完整的 n
数组图书。
您还可以分配一个指向书籍的指针数组,在这种情况下,您需要将每个指针分配给新分配的书籍。
因此您可以执行以下任一操作(并且您的代码混合了两者):
struct book** ptr = (struct book**) malloc(c * sizeof(struct book*));
struct book* ptr = (struct book*) malloc(c * sizeof(struct book));
在第一种情况下,您需要分配新书(因此循环内的 malloc
是有意义的)
在第二种情况下,您只需直接使用数组,这就是我更改以下代码的目的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book {
char title[80];
char autor[80];
int pages;
};
int comparator(const void * a, const void *b)
{
struct book * ia = (struct book*)a;
struct book * ib = (struct book*)b;
return (strcmp(ia->autor, ib->autor));
}
int main(int argc, char ** argv)
{
int c = 3;
int i;
//Pointer to array of struct pointers, malloc for 2 structs
struct book* ptr = (struct book*) malloc(c*sizeof(struct book));
if (ptr == NULL) {
printf("Could not allocate data\n");
return 1;
}
for (i = 0;i<c;i++) {
printf("Title: ");
scanf("%s", ptr[i].title);
printf("Autor: ");
scanf("%s", ptr[i].autor);
}
for (i = 0;i < c;i++) {
printf("Before Quick sort Autor: %s, Title : %s \n", ptr[i].autor, ptr[i].title);
}
qsort(ptr, c, sizeof(struct book), comparator);
printf("QSORT Done...\n\n");
for (i = 0;i<c;i++) {
printf("TEST");
printf("After quick sort: Autor: %s, Title: %s \n", ptr[i].autor, ptr[i].title);
}
free(ptr);
return 0;
}
3) 最后,测试 malloc
的结果是一个很好的做法。并调用free
当你不再需要它时。
关于C 结构体字符串快速排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32151175/