#include<stdio.h>
#include<conio.h>
#include<string.h>

int n;
char (*p)[40],*temp;
void Input();
void ABCsorting();

void Input()
{
     printf("How many persons u want to input: ");
     scanf("%d",&n); 
     p=(char*)malloc(n*40*sizeof(char));
     temp=(char*)malloc(n*sizeof(char));
     int i; 
     for(i=0; i<n ; i++)
     {
        printf("String %d: ",i+1);
        fflush(stdin);
        gets(p[i]);
     }
     printf("All strings before sorting: \n");
     /*for(i=0; i<n ; i++)
     {
           printf(" %s\n",*(p+i) );  
     } */
     for(i=0; i<n ; i++)
     printf(" %s |",p[i]);
}

void ABCsorting()
{
     int i,j;
     for(i=0; i<n-1 ;i++)
     for(j=i+1; j<n; j++)
     {
        if( strcmp((p+i),(p+j)) > 0 )
        {
            temp = (p+i);
            (p+i) = (p+j);
            (p+j) = temp;
        }
      /*  if( strcmp(p[i], p[j]) > 0)
        {
            temp=p[i];
            p[i]= p[j];
            p[j]=temp;
        }*/
     }
     printf("\nAfter Sorting: \n");
     for(i=0; i<n ;i++)
     printf(" %s |",p[i]);
}
 
 
int main()
{   
    Input();
    ABCsorting();
    getch();
    return 0;
}

Please help me find the mistake in my above source code
Thanks a lot!

>> line 20: fflush(stdin);
fflush() is only guaranteed to work with output streams, not input streams.

>> line 21: gets(p)

Two problems:

  1. never ever use gets() because it may write beyone the bounds of the array, causing your program to crash. Use fgets() instead.
  2. Variable p is an array of 40 pointers. You have to allocate memory for those pointers before they can be used. Suggest you code it something like this: char p[40][80]; , which is an array of 40 character arrays, and each array can hold up to 80 characters.

>>line 38: if( strcmp((p+i),(p+j)) > 0 )
Delete that and uncomment the algorithm on line 44.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.