【发布时间】:2020-01-04 09:12:01
【问题描述】:
我目前正在开发一个简单的 DMBS 作为大学项目。在 qsort 函数发生后,我在重建列表时遇到了一些问题。
typedef struct S_Column{
char field[32];
struct S_Column *next;
} column;
void sort(column *head, int table_size){
char *array[table_size];
int array_counter=0;
column *sort_cursor;
sort_cursor=head;
//build the array of pointers
while(sort_cursor->next!=NULL){
array[array_counter] = sort_cursor->field;
sort_cursor=sort_cursor->next;
array_counter++;
}
//sorting
qsort(array, array_counter, sizeof(char*), stringCompare);
sort_cursor=head;
//rebuild the list
for(int i = 0; i<array_counter; i++){
printf("SORTED elem %d: %s\n", i, array[i]);
strcpy(sort_cursor->field, array[i]);
sort_cursor=sort_cursor->next;
}
free(sort_cursor);
}
static int stringCompare(const void* str1, const void* str2){
return strcmp(*(const char**)str1, *(const char**)str2);
}
在排序函数中,我在将array[i] 的值复制到结构字段sort_cursor->field 时遇到问题。
特别是在//rebuild the list 部分,当我从array[i] 变量或sort_cursor->field 变量中打印出值时,输出包含复制值。
我注意到,如果我删除该部分中的 strcpy 函数,它会正确打印出所有内容。
我的目标是拥有一个column 类型的列表,其中包含正确排序的值。
【问题讨论】:
-
我在这里遗漏了一些东西:您已经描述的删除
strcpy调用不是您正在寻找的解决方案,这是怎么回事? -
我想从指针数组
array中获取值并使用这些值构建结构。