gpt4 book ai didi

c - 自定义排序函数的奇怪结果

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:59 26 4
gpt4 key购买 nike

我正在尝试创建一个排序函数,该函数接收指向动态创建的内存 (malloc) 的指针、项目总数和项目的最大大小。

我当前的函数输出一个按字母顺序排列的列表,但最后一个结果列在第一个位置。我这辈子都无法理解导致这样的输出的代码有什么问题。

int sort_array (char *array, int count, int size)
{
int i, j;
char *temp;

if((temp = malloc((size + 1) * sizeof(char))) == NULL)
{
fprintf(stderr, "sort_array: malloc failed\n");
return(RETURN_FAILURE);
}

for (i = 0; i < (count * size); i += size)
for (j = size; j < (count * size); j += size)
if (strcmp(&array[i], &array[j]) < 0)
{
strcpy(temp, &array[i]);
strcpy(&array[i], &array[j]);
strcpy(&array[j], temp);
}

return(RETURN_SUCCESS);
}

输出:

Zebra
Alpha
Delta
November
Quasar
Start
Van
Window

主要内容:

int main (int argc, char *argv[])
{
int x;
char *data = NULL;
char *temp = NULL;
struct dirent *filename;
char *path = "/testing/i/m";
int count = 0;
DIR *dir;

if((dir = opendir(path)) != NULL)
{
while((filename = readdir(dir)) != NULL)
{
if(filename->d_name[0] != '.')
{
if((temp = realloc(data, (count + 1) * FIELD_SIZE * sizeof(char))) == NULL)
{
free(data);
fprintf(stderr, "main: realloc failed\n");
exit(EXIT_FAILURE);
}

data = temp;
strcpy(&data[count++ * FIELD_SIZE], filename->d_name);
}
}

closedir(dir);
}
else
{
fprintf(stderr, "main: unable to read directory contents\n");
exit(EXIT_FAILURE);
}

sort_array(data, count, FIELD_SIZE);

for(x = 0; x < count; x++)
printf("%s\n", &data[x * FIELD_SIZE]);

exit(EXIT_SUCCESS);
}

最佳答案

您的排序例程的内部循环处理了太多项目,而且似乎应用了错误的顺序。要按升序正确排序,请执行以下操作:

for (i = 0; i < (count * size); i += size)
for (j = size; j < (count * size); j += size)
if (strcmp(&array[i], &array[j]) < 0)

应该是这样的:

for (i = 0; i < (count * size); i += size)
for (j = i + size; j < (count * size); j += size)
if (strcmp(&array[i], &array[j]) > 0)

关于c - 自定义排序函数的奇怪结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com