1

I wish to sort the strings alphabetically using swap function. The swap function doesn't seems to work. Should i pass the entire array of strings into swap as well ?

#include <stdio.h>
#include <string.h>
void swap (char *s, char *t);
void main()
{
    char *name[10] = {"Noida","Lucknow","Kanpur","Mohali","Chandigarh","Mumbai","Kerala","Chennai","Bangalore","Indore"};
    char *temp;
    printf("The names are :\n");
    for(int i = 0; i < 10; i++)
    {
        printf("%s\n",name[i]);
    }
    printf("\nSORTING ALPHABETICALLY - \n\n");
    for (int i = 0; i < 10; i++)
    {
        for (int j = i + 1; j < 10; j++)
        {
            if(strcmp(name[i],name[j])>0)
                swap(name[i],name[j]);
        }
    }
    for(int i = 0; i < 10; i++)
    {
        printf("%s\n",name[i]);
    }
}
void swap (char *s, char *t) //Not swapping
{
    char *temp;
              temp = s;
              s = t;
              t = temp;
}
5
  • 1
    You are swapping the function arguments, not what they point to. These are copies of what you passed, which are then forgotten. Commented Mar 11, 2019 at 8:09
  • So how to make this change reflect in the main() ? Commented Mar 11, 2019 at 8:13
  • 1
    I suggest the function should take the array (pointer), and the indices of the two elements to be swapped, or, as one answer. Commented Mar 11, 2019 at 8:14
  • Possible duplicate of strings swap in c Commented Mar 11, 2019 at 8:26
  • Instead of writing your own sorting code you should use qsort Commented Mar 11, 2019 at 8:32

1 Answer 1

5

You are passing the pointers by copy. The function operates on its own local variables which are copies of the pointers to those strings, not the pointers to the main variables. So it can change the strings but not those variables(= values of those pointers). This should fix it:

void swap (char **s, char **t) 
{
    char *temp;
    temp = *s;
    *s = *t;
    *t = temp;
}

Edit: As stated in the comment bellow: Then call it like swap(&name[i],&name[j]);

Sign up to request clarification or add additional context in comments.

2 Comments

And of course changing the function call to swap(&name[i], &name[j]);.
@Blaze or just swap( name+i, name+j );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.