Hi again,
I have modified my code.. can you please review it now and give me suggestions
Code:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define MAXLENGTH 20 /*maxlength defined for array to accept names */
void insertion (char *a[], int n);
int
main (void)
{
int num, i;
char name[MAXLENGTH];
char **namelist;
printf ("\nEnter the number of names you want to enter >");
scanf ("%d", &num);
/*An array of pointers is created dynamically and checked for allocation errors */
if ((namelist = calloc (num, sizeof (char *))) == NULL)
{
printf ("\nError allocating memory");
exit (1);
}
/*
The loop is run num number of times and names are accepted
into the fixed length array name. And memory is dynamically allocated for the length of name
and the contents are transfered
*/
for (i = 0; i < num; i++)
{
printf ("Enter name %d>", i + 1);
scanf ("%19s", name);
if ((*(namelist + i) =calloc (strlen (name), sizeof (char))) == NULL)
{
printf ("\nError allocating memory");
for (i--; i >= 0; i--) /* If an error occurs allocating memory the previous allocations are aslo deallocated and the program quits */
free (*(namelist + i));
free (namelist);
exit (1);
}
else
strcpy (*(namelist + i), name); /*The name is transfered to the newly allocated space */
}
insertion (namelist, num); /*The sort function is called */
printf ("\nSORTED ARRAY:\n");
/*
The sorted array is printed and after each print the specific space is deallocated
*/
for (i = 0; i < num; i++)
{
printf ("\n %s", *(namelist + i));
free (*(namelist + i));
}
free (namelist);
printf ("\n");
return 0;
}
void
insertion (char *a[], int n)
{
int i, num;
char *temphold; /*Temporary Variable to hold a pointer address when swaping pointers */
for (i = 1; i < n; i++) /*Loop is run n number of times which is the number of elements */
{
num = i; /*The value of i is copied into num for manipulation in the while loop */
/*
The while loop is run until all the elements in the left section of the array are sorted
*/
while (strcmp (*(a + num), *(a + num - 1)) < 0)
{
temphold = *(a + num); /*Swapping part */
*(a + num) = *(a + num - 1);
*(a + num - 1) = temphold;
if (num - 1 == 0) /*(While) loop terminated on reaching 1st element of the array */
break;
else
num--; /*Num is decremented to compare previous elements inside a given section */
}
}
return;
}
thanx in advance
bye