So it's the third week of my life in C and I've been given the task of writing a program which takes in upto 100words which are upto 80characters long, calculates the average word length of the inputs, prints words larger than the average, and finally prints the average word size. EDIT: We also have to use an emalloc, a recursive output method, and free all used memory.
Success! ... or so I thought.
I wrote the following within Eclipse which uses gcc -E -P -v -dD
as its compilation arguments, and I get no runtime errors whilst running the program using the provided testcases.
Now I have completed the code I have to reproduce it during a 30min practical. We are told we have to use a text editor and that gcc -W -Wall -ansi -pedantic
will have to be used as the compilation arguments, but if I use these arguments instead it means my program always exits with `Bus error'
EDIT: Fixed and Formatted
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXIMUM_STRING_LENGTH 80
#define MAXIMUM_ARRAY_LENGTH 100
void* memory_allocation(size_t sizeof_memory_required) {
void* free_memory_pointer = malloc(sizeof_memory_required);
if (free_memory_pointer/*exists*/) {
return free_memory_pointer;
} else {
fprintf(stderr, "*** MEMORY ALLOCATION FAILURE ***\n");
exit(EXIT_FAILURE);
}
}
void print_larger_than_average_strings(char** string_pointers, int i, const double AVERAGE_STRING_LENGTH) {
if (string_pointers[i]/*exist*/) {
if (strlen(string_pointers[i]) > AVERAGE_STRING_LENGTH) {
printf("%s\n", string_pointers[i]);
}
print_larger_than_average_strings(string_pointers, ++i, AVERAGE_STRING_LENGTH);
} else {
fprintf(stderr, "%.2f\n", AVERAGE_STRING_LENGTH);
}
}
int main(void) {
int string_count = 0;
char string[MAXIMUM_STRING_LENGTH];
char* string_pointer[MAXIMUM_ARRAY_LENGTH];
int i;
double character_count;
while ((string_count < MAXIMUM_ARRAY_LENGTH) && (1 == scanf("%79s", string))) {
string_pointer[string_count] = memory_allocation(sizeof string_pointer[0][0] * (strlen(string) + 1));
strcpy(string_pointer[string_count++], string);
}
string_pointer[string_count] = NULL;
for (i = 0; i < string_count; i++) {
character_count += strlen(string_pointer[i]);
}
if (string_count/*exists*/) {
print_larger_than_average_strings(string_pointer, 0, character_count / string_count);
for (i = 0; i < string_count; i++) {
free(string_pointer[i]);
}
}
return EXIT_SUCCESS;
}