I am trying to write a C program which takes input from a .txt file, stores the words in an array of char pointers, averages the word length and prints out any words which exceed the average length. Right now I am trying to get a print function working (print_array), I want to do this recursively. For some reason the print function is not printing out all elements of the array, it is only printing the first element and removing the first character each time. What am I doing wrong here? Cheers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAYLEN 100
#define CHARLEN 79
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
void print_array(char *a, int n) {
if (n > 0) {
printf("%s\n", &a[0]);
print_array(a + 1, n - 1);
}
}
int main(void) {
char word[CHARLEN];
char *wordlist[ARRAYLEN];
double average;
int num_words;
num_words = 0;
average = 0.0;
while (num_words < ARRAYLEN && 1 == scanf("%79s", word)) {
wordlist[num_words] = emalloc((strlen(word) + 1) * sizeof wordlist[0][0]);
strcpy(wordlist[num_words], word);
average += strlen(word);
num_words++;
}
average = average / num_words;
printf("Average is %.2f\n", average);
print_array(*wordlist, num_words);
return EXIT_SUCCESS;
}
Output -
Average is 9.71
hello
ello
llo
lo
o
char word[CHARLEN];is 1 too small for"%79s".CHARLEN, it would be better to use"%" #CHARLEN "%s".