Sorting city names fails
I want to sort the inputted city names but below code gives me such as:
Ýnput:
Newyork Georgetown Berlin
Output:
Berlin Gewyork Beorgetown
Why is that?
I was thinking to compare with strcmp and swap the pointers then but it
seeems it is not working.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *dummy);
void swap(char *first, char *second);
int i;
char *names[3];
char *temp;
int main(void){
//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < 3; i++)
{
names[i]=malloc(100);
fgets( names[i], 99, stdin);
}
//print entered names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}
sort(names);
//print sorted names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}
getch();
}
//sorting function
void sort(char *dummy){
for (i = 0; i < 2; i++)
{
if (strcmp( &dummy[i], &dummy[i+1]) >0)
{
swap(&dummy[i], &dummy[i+1]);
}
}
}
//swapping function
void swap(char *first, char *second){
temp=second;
second=first;
first=temp;
}
No comments:
Post a Comment