Вопрос

First i take signs from txt and create string "znaky" where i put them. After that i sort only numbers from string and take them to another string "cifry" after that i want to sort them with qsort but there is some problem program crased. Can anyone help me please??

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

int main()
{
    const int POCET=10;
    char *znaky=(char *)malloc(POCET*sizeof(char));
    char *cifry=(char *)malloc(POCET*sizeof(char));
    char *hladaneZnaky="0123456789";
    char *nasiel;
    char znak;
    int pocetPrvkov=-1;
    int kolkoKratAlokoval=1;
    FILE *fr;

    if((fr=fopen("zdroj.txt","r"))==NULL)
    {
        printf("Subor zdroj.txt neexistuje!\n");
        return 1;
    }

    while(fscanf(fr,"%c",&znak)!=EOF)
    {
        pocetPrvkov++;
        if(pocetPrvkov%POCET==POCET-1)
        {
            kolkoKratAlokoval++;
            znaky=(char *)realloc(znaky,POCET*kolkoKratAlokoval*sizeof(char));
        }
        znaky[pocetPrvkov]=znak;
    }
    printf("%s\n\n",znaky);
    pocetPrvkov=0;
    kolkoKratAlokoval=1;
    nasiel=strpbrk(znaky,hladaneZnaky);
    while(nasiel!=NULL)
    {
        if(pocetPrvkov%POCET==POCET-1)
        {
            kolkoKratAlokoval++;
            cifry=(char *)realloc(cifry,POCET*kolkoKratAlokoval*sizeof(char));
        }
        cifry[pocetPrvkov++]=*nasiel;
        nasiel=strpbrk(++nasiel,hladaneZnaky);
    }
    cifry[pocetPrvkov]='\0';
    printf("%s\n\n",cifry);
    pocetPrvkov++;
    qsort(cifry,pocetPrvkov,sizeof(char*),comp);
    printf("%s\n",cifry);
    free(znaky);
    fclose(fr);
    return 0;
}

int comp(const void *a,const void *b)
{
    return strcmp(*(char **)a,*(char **)b);
}
Это было полезно?

Решение

cifry is of type char*. So your comparison function should have just:

strcmp((const char *) a, (const char *) b);

Другие советы

It should have been char **cifry (it is used as a char *cifry[]). The asignment to cifry[pocetPrvkov++] advances by one character, not a pointer, and your data array gets mangled before even trying to sort it.

Compiling this with modest optimization and full warnings should have made the mismatch evident...

It is good practice to define functions to print out data, in this case you should have printed out the unsorted data (at least for debugging, but it might be useful to have the user of the program be able to check the input is as intended).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top