qsort更改传递的数组长度整数的值

  • 本文关键字:整数 数组 qsort c
  • 更新时间 :
  • 英文 :


我将一个大小为10的链表传递给sort_nodes,旁边还有一个int。然而,当我使用快速排序时,我的程序";"停止";,并且它似乎不执行第二打印节点功能。出于某种原因,我的CLion编译器给了我一个";无法分解功能";错误,所以我甚至使用调试器都没有成功。

int main(void){
node_ptr *head;
int num_of_nodes = load_nodes(head); // returns the number of items loaded, in this case it is going to be 10
print_all_nodes(head); 
sort_nodes(head,num_of_nodes); 
print_all_nodes(head); // check that the items have been sorted correctly
}

void insert_node(node_ptr *head_ptr, node_ptr insertion){
if (*head_ptr != NULL){ // if the header has a pointer
printf("Inserting new item at headn");
insertion->next = *head_ptr;
}
else{
printf("Head is null so assigning head to new pointern");
}
*head_ptr = insertion;
}
int compare_strings(const void *p1, const void *p2){
competitor *competitor1, *competitor2;
node1= (node *) p1;
node2 = (node *) c2;
return strcmp(node1->some_string,node2 ->some_string);
}
void delete_linked_list(node_ptr *head_ptr){
node_ptr current_temp_ptr = *head_ptr;
node_ptr next_temp_ptr = NULL;
while (current_temp_ptr != NULL){
next_temp_ptr = current_temp_ptr->next;
free(current_temp_ptr);
current_temp_ptr = next_temp_ptr;
}
head_ptr = NULL;
}

void sort_nodes(node_ptr *head_ptr, const int num_of_nodes){
printf("Num of nodes: %dn",num_of_nodes); // expected 10 got 10;
node_ptr nodes[num_of_nodes]; // array used for sorting
node_ptr temp_ptr = *head_ptr; 
printf("temp pointer set upn");
for (int i=0; i<num_of_nodes; i++){
temp_ptr = temp_ptr->next; // get next (first) node
nodes[i] = temp_ptr;
}
delete_linked_list(head_ptr);
printf("Num of nodes: %d",num_of_nodes); //expected 10, got 10
qsort(&nodes,num_of_nodes, sizeof(node), compare_strings);
printf("Num of nodes= %d", num_of_nodes); // expected 10, got -2145129072
for (int i=0; i<num_of_nodes; i++){
insert_node(head_ptr,nodes[i]);
}
}

很抱歉有任何拼写错误,我不得不更改名称,使问题更普遍

至少这些问题

错误类型

p1, p2是指向nodes_ptr的指针,而不是指向node的指针。回想一下,p1, p2是指向数组元素的指针,而数组是nodes_ptr nodes[num_of_nodes]

int compare_strings(const void *p1, const void *p2){
// competitor *competitor1, *competitor2;
// node1= (node *) p1;
// node2 = (node *) c2;
const nodes_ptr *node1 = (const nodes_ptr *) p1;
const nodes_ptr *node2 = (const nodes_ptr *) p2;
// return strcmp(node1->some_string,node2 ->some_string);
return strcmp((*node1)->some_string, (*node2)->some_string);
}

元件尺寸错误,不需要&

与其将大小调整为元素sizeof(node)的类型(并像OP那样使用错误的类型(,不如将大小调整至数组元素sizeof nodes[0]。更容易正确编码。

nodes_ptr nodes[num_of_nodes]; // array used for sorting
....
// Drop  v                     wrong size              
// qsort(&nodes,num_of_nodes, sizeof(node), compare_strings);
qsort(nodes, num_of_nodes, sizeof nodes[0], compare_strings);

最新更新