I am trying to a simple string sorting function since I am now learning array and string lesson. however, my function is not working as I expected.
Could you please help debugging the code below?, I have a problem at the function sort.
I cannot correctly sort the string passed to the function in order at all.
Code:
#include <stdio.h>
#include <string.h>
#define MAXLINES 28
char *lines[MAXLINES];
int get_lines(char *lines[]);
void sort(char *p[], int n)
{
int b;
char *x;
for (b = 0; b < n-1; b++)
{
if (strcmp(p[b], p[b+1]) > 0)
{
x = p[b];
p[b] = p[b+1];
p[b+1] = x;
}
}
}
main()
{
int number_lines = 0;
number_lines = get_lines(lines);
if ( number_lines < 0 ) {
printf("\nMemory allocation error!");
exit (-1);
}
sort(lines, number_lines);
return 0;
}
int get_lines(char *lines[])
{
int n = 0;
char buffer[80]; // temporary storage for each line
puts("Enter one line at a time; enter a blank when done.");
while ( (n<MAXLINES) && (gets(buffer)!= 0) && (buffer[0]!='\0') )
{
if ( (lines[n] = (char *) malloc(strlen(buffer)+1))== NULL )
return -1;
strcpy (lines[n++], buffer);
}
return n;
}