But what if something goes wrong? You'll need to be able to report an
error. The natural way to do this is via a return value, which means we
can't use that value for either the list or the count, and that leads us
to:
what we will do with that return value ? If something wrong occurs I can
simply exit the program telling the user that he did some thing stupid and
he is responsible for that.
int get_words(char ***, size_t *);
Since they don't need to modify the caller's status, sort_words and
print_words can be of type int(char **, size_t).
I think there is qsort in std. lib. , hence we can use that but I don't
know whether it modifies the original array or not.
Up to you, but I wouldn't bother setting a limit (or, if I did, I'd set it
at a million or so, and treat any string longer than that as a reportable
error). With dynamic allocation, you don't /need/ to set a limit; you
simply allocate as you go, and reallocate if necessary.
okay, I will write the program in parts. First we will write a simple
program that will ask the user to input and we will store that word
dynamically using calloc in some array. It will be called get_single_word
and it will form the basis of get_words function which will store all
words in an array. get_single_word returns an int because I want to use
get_single_word in get_words like this:
while( get_single_word )
{
/* code for get_words */
}
Here is my code for get_single_word. PROBLEM: it does not print anything
I entered:
/* a program to get a single word from stdin */
#include <stdio.h>
#include <stdlib.h>
enum { AVERAGE_SIZE = 28 };
int get_single_word( char* );
int main( void )
{
char* pw; /* pw means pointer to word */
get_single_word( pw );
printf("word you entered is: %s\n", pw);
return 0;
}
int get_single_word( char* pc )
{
int idx;
int ch;
char *pc_begin;
pc = calloc(AVERAGE_SIZE-1, sizeof(char));
pc_begin = pc;
if( (! pc) )
{
perror("can not allocate memory, sorry babe!");
return 1;
}
for( idx = 0; ( (ch = getchar()) != EOF ); ++idx, ++pc )
{
if( AVERAGE_SIZE == idx )
{
/* use realloc here which I have no idea how to write */
}
*pc = ch;
}
*++pc = '\0';
free(pc_begin);
return 0;
}
=================== OUTPUT ==================
[arnuld@dune ztest]$ gcc -ansi -pedantic -Wall -Wextra test.c
[arnuld@dune ztest]$ ./a.out
like
word you entered is:
[arnuld@dune ztest]$