I'm trying to write a code that sorts an array of strings in alphabetical or reverse alphabetical order, depending on the command line argument given.
"-o a" for alphabetic.
"-o r" for reverse.
This is my code so far.
#include<stdio.h>
#include<string.h>
int string_compare(char *str1,char *str2){
int ret;
ret=strcmp(str1,str2);
if(ret < 0) {
return 0;
}
else if(ret > 0) {
return 1;
}
else {
return -1;
}
}
void swap(char *str1, char *str2)
{
char *temp = str1;
str1 = str2;
str2 = temp;
}
int main(int argc,char *argv[]){
char *planets[9]={"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
int i,j;
int a_ret=strcmp(argv[2],"a");
int r_ret=strcmp(argv[2],"r");
int cmp;
for(i=0;i=8;i++){
for(j=8;j=(i+1);j--){
cmp=string_compare(planets[j],planets[j-1]);
if(a_ret==0){
if(cmp==0){
swap(planets[j],planets[j-1]);
}
}
else if(r_ret==0){
if(cmp==1){
swap(planets[j],planets[j-1]);
}
}
}
}
printf("%s",planets[0]);
return 0;
}
The program is supposed to work something like this:
./planets –o a
The planets in alphabetical order are: Earth, Jupiter, Mars, Mercury, Neptune, Pluto, Saturn, Uranus, Venus
or this:
./planets –o r
The planets in reverse alphabetical order are: Venus, Uranus, Saturn, Pluto, Neptune, Mercury, Mars, Jupiter, Earth
The program compiles without error, but when I run it I get
Segmentation fault(core dumped)
I'm new to C, and I don't quite fully understand how to manipulate the memory allocation. Any help or advice is much appreciated.