gpt4 book ai didi

c - C 中的字符串排序

转载 作者:行者123 更新时间:2023-11-30 16:57:02 26 4
gpt4 key购买 nike

嗯,我正在尝试按 C 语言文件中的字母顺序对字符串进行排序,但我的程序不起作用。我认为动态数组的内存分配错误,但我找不到它。

        #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define buflen 42
int comp(const void * a, const void * b) {
const char *arraya = *(const char**)a;
const char *arrayb = *(const char**)b;

return strcmp(arraya, arrayb);
}
char* getarray(FILE *input)
{
char buffer[buflen];
char* result = NULL;
size_t chargot = 0;
size_t fact = 0;
size_t wasinarray = 0;
while (fgets(buffer, buflen, input))
{
chargot = strlen(buffer);
fact += chargot;
if (fact >= wasinarray)
{
wasinarray += buflen;
result = realloc(result, wasinarray);
strcat(result, buffer);
}
if (buffer[chargot - 1] == '\n')
break;
}
if (ferror(stdin))
{
if (result)
free(result);
return NULL;
}
return result;
}


int main() {
char **strarray = NULL;
int i = 1, strcount = 0;
char* strline;
FILE *input, *output;
input = fopen("input.txt", "r");
output = fopen("output.txt", "w");
strarray = (char**)malloc(i * sizeof(char*));
while (strline = getarray(input) != NULL)
{
strarray[strcount] = strline;
strarray = (char**)realloc(strarray, (i + 1) * sizeof(char*));
strcount++;
i++;
}
qsort(strarray, strcount, sizeof(char**), comp);
for (i = 0; i < strcount; i++)
{
fprintf(output, "%s", strarray[i]);
free(strarray[i]);
}

free(strarray);
free(strline);
close(output);
close(input);
return 0;
}

输入和输出必须是这样的

输入:

 dfsdfds
asfsdfds
badgfdgfd
csdfdsgfd

输出:

 asfsdfds 
badgfdgfd
csdfdsgfd
dfsdfds

最佳答案

像这样修复:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define buflen 42

int comp(const void * a, const void * b) {
return strcmp(*(const char**)a, *(const char**)b);
}

char* getarray(FILE *input){
char buffer[buflen];
char* result = NULL;
size_t chargot = 0;
size_t fact = 0;

while (fgets(buffer, buflen, input)){
chargot = strlen(buffer);
result = realloc(result, fact + chargot + 1);
memcpy(result + fact, buffer, chargot + 1);
fact += chargot;
if (buffer[chargot - 1] == '\n')
return result;
}
return NULL;
}

int main(void){
char **strarray = NULL;
int i = 0, strcount = 0;
char* strline;
FILE *input, *output;

input = fopen("input.txt", "r");
output = fopen("output.txt", "w");

while ((strline = getarray(input)) != NULL){
strarray = realloc(strarray, (i + 1) * sizeof(char*));
strarray[i++] = strline;
}

qsort(strarray, (strcount=i), sizeof(char*), comp);
for (i = 0; i < strcount; i++){
fprintf(output, "%s", strarray[i]);//!!Input line includes always newline
free(strarray[i]);
}

free(strarray);
fclose(output);
fclose(input);
return 0;
}

关于c - C 中的字符串排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39688206/

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