> On Tue, 22 Apr 2008 13:05:13 +0100, Ben Bacarisse wrote:
> I would not link these two sizes. You need two enum constants.
it is done.
> The second parameter has a bad name. At best it is one line.
sorry, my mistake
> I'd stick with reading the lines in first. Deal with sorting later.
okay, I am done with reading and printing lines now. It is working now, I
need to understand the sorting part now:
/* write a program to read a set of lines from input and sort them
* and then print them.
*
* version 1.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum MAXLINES { ARR_SIZE = 100, STR_SIZE = 1000 };
char* arr_of_ptr[ARR_SIZE];
char arr_of_char[STR_SIZE];
int readlines( char**, const int );
void printlines( char** );
/* main() will simply call the other functions to do the job */
int main( void )
{
if( readlines( arr_of_ptr, ARR_SIZE ) > 0 )
{
/* qsort( arr_of_ptr, ARR_SIZE, sizeof( char* )); */
printlines( arr_of_ptr );
}
else
{
fprintf( stderr, "error: out of memory\n" );
}
return 0;
}
/* 1) read lines till we get the NULL,
* 2) store those lines into an array of characters <arr_of_lines>,
* 3) pointer of arry of pointers <arr_of_ptr> will point to the
* individual elements of array of characters <arr_of_lines>,
*
*/
int readlines( char* arr_of_ptr[], const int max )
{
char *p, **p_arrptr;
int num_lines, size_arr;
char temp_arr[STR_SIZE];
num_lines = 0;
p_arrptr = arr_of_ptr;
while( fgets(temp_arr, max, stdin) && num_lines < max )
{
size_arr = strlen( temp_arr ) + 1;
if( (p = malloc( size_arr * sizeof( char ))) )
{
strcpy( p, temp_arr );
*p_arrptr++ = p;
++num_lines;
}
}
return num_lines;
}
/* it will simply print the lines pointed to by the elements of
* arrays of pointers <arr_of_ptr>.
*
*/
void printlines( char* arr_of_ptr[] )
{
printf("\n-------------------------\n");
while( *arr_of_ptr )
{
printf("%s", *arr_of_ptr++ );
}
}
============= OUTPUT ===================
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra 5-7.c
/home/arnuld/programs/C $ ./a.out
Ben & Richard
both are helping
C newbie.... arnuld
-------------------------
Ben & Richard
both are helping
C newbie.... arnuld
/home/arnuld/programs/C $
--
http://lispmachine.wordpress.com/
my email ID is at the above address