JustBeginner JustBeginner - 2 months ago 7
C Question

Sorting string in C

Well, i'm trying to sort strings alphabetically from file in C, and my program doesn't work. I think mistake in memory allocation for dynamic array, but i can't find it.

#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;
}


Input and output must be like this

Input:

dfsdfds
asfsdfds
badgfdgfd
csdfdsgfd


Output:

asfsdfds
badgfdgfd
csdfdsgfd
dfsdfds

Answer

fix like this:

#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;
}
Comments