The program is expected to sort and display a list of words from a array whose elements are pointers to char. I use malloc to alocate space to each element and use a read_line function to store in the element the typed word. The issue rests on the garbage of random characters that has each word as though the program wasn't able to read my typed characters and store them.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100
#define LEN 20
int string_compare(const void *n, const void *m);
int read_line(char *str, int n);
int main(void)
{
int i, num_words, largo;
char *list[MAX], word[LEN+1];
for (i=num_words=0; i<MAX; i++, num_words++) {
printf("Enter word: ");
list[i] = malloc(LEN + 1);
if (list[i] == NULL) {
printf("Error, no more memory available\n");
break;
}
largo = read_line(word, LEN) ; // no sé por qué la string
if (largo == 0) // que recoge la funcion
break; // el break ya va // son char random (garabage)
printf("Copying string %s...\n",list[i]);
strcpy(list[i], word);
}
qsort(list, i, 21 * sizeof(char), string_compare);
printf("In sorted order: ");
for (i=0; i < num_words; i++)
printf("Displaying...\n");
printf("%s ", list[i]);
return 0;
}
int string_compare(const void *n, const void *m)
{
return strcmp((char *) n, (char *) m);
}
int read_line(char *str, int n)
{
int ch, i=0;
while ((ch=getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}
I used strcpy, strcat and altered the order of reading and allocation code lines without successs.
listas an array of arrays, which it is not. It's an array of pointers. So that means the element size issizeof(char *)and the comparison function receives pointers to the pointers (i.e.char **).