In this C program I read in words typed with my keyboard to a char pointer. The pointer is stored in an pointer array. Then I want to sort the array with qsort by the function comparison. I give it the pointer to my pointer array. It doesnt sort the array at all. I dont know if I got here a UB, or I miss memory by wrong allocation.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool read_word(char ***a, int *length);
int comparison(const void *p, const void *q);
int main()
{
int *length = malloc(sizeof(int));
*length = 0;
char **array = malloc(sizeof(char *));
bool go = false;
while(go == false)
{
printf("Enter word: ");
go = read_word(&array,length);
}
qsort(array, *length - 1,sizeof(char *), comparison);
printf("\n");
for(int i = 0; i < *length; i++)
printf("%s\n", array[i]);
return 0;
}
bool read_word(char ***a, int *length)
{
char ch;
++*length;
char *word = malloc(20 * sizeof(char) + 1);
char *keep_word;
char **temp = realloc(*a,*length * sizeof(*a));
if(!temp)
exit(EXIT_FAILURE);
*a = temp;
keep_word = word;
while((ch = getchar()) != '\n')
*keep_word++ = ch;
*keep_word = '\0';
if(word == keep_word)
{
free(word);
--*length;
return true;
}
(*a)[*length - 1] = word;
printf("%s", (*a)[*length -1]);
printf("\nh\n");
return false;
}
int comparison(const void *p, const void *q)
{
const char *p1 = p;
const char *q1 = q;
return strcmp(p1,q1);
}