This program ask to the user to enter words, then it shows the words sorted. My question is If I've used correctly malloc and realloc correctly since I'm still proccessing the concept of pointer to pointer but anyways I tried to go for it, trying to allocated and array of strings dynamically.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LEN 20
int read_line(char str[], int n);
int compar_string(const void *p, const void *q);
int main(void)
{
char buffer[WORD_LEN+1], **words;
int n = 10;
int j;
words = malloc(n * sizeof(char *)); //Allocating space for an array of strings
if (words == NULL) {
printf("malloc failed.\n");
exit(EXIT_FAILURE);
}
for (j = 0;; j++) {
if (j < n) {
printf("Enter a word:");
if(read_line(buffer, WORD_LEN)) {
words[j] = malloc(strlen(buffer)+1);
strcpy(words[j],buffer);
} else
break; //Break from loop if an empty word is entered
} else {
char **temp;
n *= 2;
temp = realloc(words, n * sizeof(char *)); //reallocating space if the user enters more than 10 words
if(temp == NULL) {
printf("realloc failed.\n");
exit(EXIT_FAILURE);
} else {
printf("array reallocated.\n");
words = temp;
j--;
}
}
}
qsort(words, j, sizeof(words[0]), compar_string); //sorting the array of strings
printf("In sorted order: ");
for(int i = 0; i < j; i++)
printf("%s ", words[i]);
printf("\n");
return 0;
}
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;
}
int compar_string(const void *p, const void *q)
{
return strcmp(*(char **)p, *(char **)q);
}
This function also gave me questions, it's an example that the book shows for use strcmp with qsort
Code:
int compar_string(const void *p, const void *q)
{
return strcmp(*(char **)p, *(char **)q);
}
If I declare a char **p, the variable p is a pointer to a pointer that points to a char right? If later in the program I use *p, im refering to the "pointer that points to the char? [ p ] -> [ char * ](Is this *p?) -> char
Im I correct?