When I compile this code as it is, I get this error:
variable-sized object 'word_list' may not be initialized
char *word_list[i] = malloc(sizeof(char) * STRING_LENGTH );
I know on line 13 my variable word_list is just a pointer to characters and that it is causing the problem. I have to use an array of pointers instead of it but I am not sure how to do this properly. The word_list variable is supposed to be an array that is to have strings copied into it using strcpy.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define STRING_LENGTH 20
#define MAX 30
int read_string(char string[], int n);
int compare(const void*a, const void*b);
int main(){
int i;
char* word_list;
char word[STRING_LENGTH + 1];
for (i = 0; ; i++){
printf("\nEnter a word.\n");
read_string(word, STRING_LENGTH);
if (word[0] == '\0')
break;
char *word_list[i] = malloc(sizeof(char) * STRING_LENGTH );
free(word_list);
strcpy(word_list[i], word);
}
int length = sizeof(word_list)/sizeof(char*);
int j;
for (j = 0; word_list[j] != '\0'; j++)
printf("%s\n", word_list[j]);
qsort(word,length, sizeof(char*), compare);
for (j = 0; word_list[j] != '\0'; j++)
printf("%s\n", word_list[j]);
return 0;
}
int compare(const void*element1, const void *element2){
const char *string1 = *(const char**)element1;
const char *string2 = *(const char**)element2;
return strcmp(string1,string2);
}
int read_string(char string[], int n){
int ch, i = 0;
while ((ch = getchar()) != '\n')
if (i < n)
string[i++] = ch;
string[i] = '\0';
return i;
}
free(word_list)immediately after you (try to) allocate it?