I have a collection of strings of planet names in c. I have stored them in a character array. I want to sort them out. I know there's a string comparing method in c but I need to implement mine. In my method(string_compare(char *planet1, char *planet2)), i check characters between two planets. If character of planet1 is after that of plannet2, then I return 1, else 0 is returned. I then rearrange the array items accordingly. At the moment, my loop is not exiting. It is running infinetely. I am also having trouble exchanging the array entries. Please assist.
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
//method declaration
int string_compare(char *planet1, char *planet2);
//main method
int main () {
char *planets[9]= {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
bool sorted=false;
int i=0, count = 0;
do{
int planets_size = (int)sizeof(planets)/sizeof(planets[0]);
for(i=0; i< planets_size-1;i++){
char *planet1_pointer = planets[i];
char *planet2_pointer = planets[i+1];
int comparison = string_compare(planet1_pointer,planet2_pointer);
if(comparison>1){
planets[i] = planet2_pointer;
planets[i+1] = planet1_pointer;
sorted = false;
break;
} else {
if(i==planets_size-1){
sorted = true;
}
}
}
count++;
} while (sorted==false);
printf("The planets in alphabetical order are ");
//printf("%s",planets);
i=0;
for (i=0; i<9; i++) {
printf("%s " , planets[i]);
}
return 0;
}
int string_compare(char *planet1, char *planet2){
int planet1_size = strlen(planet1);
int planet2_size = strlen(planet2);
int size=0;
if(planet1_size<planet2_size){
size = planet1_size;
} else{
size = planet2_size;
}
int i=0;
for(i=0; i < size;i++){
if((int)planet1[i]<(int)planet2[i]){
return 0;
} else if((int)planet1[i]>(int)planet2[i]){
return 1;
} else {
continue;
}
}
return 0;
}
My code is above. I am a beginner in c.
sizeofon a pointer, you only get the size of the pointer and not what it points to. To get the length of the string, either usestrlen, or if you must make the code yourself (as an exercise) remember that strings in C are terminated by the character'\0'.if(i==planets_size){Never be true.for()loop with ado... while()loop. that will not work, the result is thefor()loop is run to completion. the thewhile()loop is entered (and if entered, never exits.strcmp()function instead of writing thestring_compare()function.