Я могу успешно показать слова текста. Но я не могу сортировать по алфавиту.Прочитайте большой текстовый файл и быстро отсортируйте его по алфавиту в программе C
Как вставить слова слова в текст myArray = (char) malloc (size);
Это мой код:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
static int compare (const void * a, const void * b);
int main(int argc, char *argv[])
{
FILE *fp;
char ch;
int size = 0;
fp = fopen("data.txt", "r");
if (fp == NULL)
printf("\nFile unable to open ");
else
printf("\nFile opened ");
fseek(fp, 0, 2); /* file pointer at the end of file */
size = ftell(fp); /* take a position of file pointer un size variable */
//char *myArray = (char*)malloc(size * sizeof *myArray);
char *myArray = (char*)malloc(size);
static const char filename[] = "data.txt";
FILE *file = fopen(filename, "r");
if (file != NULL){
int ch, word = 0, index= 0,index2 = 0;
while ((ch = fgetc(file)) != EOF){
if (isspace(ch) || ispunct(ch)){
if (word){
word = 0;
myArray[index++] = '\n';
//putchar('\n');
}
}else{
word = 1;
//putchar(ch);
myArray[index++] = ch;
index2++;
}
}
printf("%s", myArray);
fclose(file);
int i;
for(i = 0;i < sizeof(myArray);i++){
putchar(myArray[i]);
}
//qsort (array, 2, sizeof (const char *), compare);
//for (int i = 0; i < 2; i++) {
// printf ("%d: %s.\n", i, array[i]);
//}
}
}
static int compare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
Вы не можете использовать оператор 'sizeof' для определения количества элементов в массиве, выделенных через' malloc() '. Кстати, почему второй аргумент 'qsort()' в комментарии 2? Потому что это 'sizeof (myArray)' в каком-то 16-битном enviromnent? – MikeCAT
Потому что до того, как я положил два слова в массив символов, так что hardcode 2. На самом деле, я не знаю, как четко заполнить данные массиву char и как получить размер. – kennethk
Что произойдет, если вы попытаетесь запустить код? Предоставляет ли она ошибку компиляции, ошибку времени выполнения или неправильные результаты? Если последний, пожалуйста, укажите ожидаемый результат и фактический результат. – anatolyg