0

So i am trying to sort an array of strings but i have no ideea how to pass it to the function.Also, what would be the equivalent of this code but using pointers?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sort(int *s)
{
    for(int i=0;i<n;i++)
        for(int j=i+1;j<n;j++)
           if(strcmp(s[i],s[j])>0)
           {
               char aux[100];
               strcpy(aux,s[i]);
               strcpy(s[i],s[j]);
               strcpy(s[j],s[i]);
           }


}
int main()
{
   char s[3][100];

   for(int i=0;i<3;i++)
      scanf("%s",s[i]);
sort(s);


    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Michael
  • 82
  • 5
  • 1
    Does this answer your question? [Sorting an array of strings in C](https://stackoverflow.com/questions/12523563/sorting-an-array-of-strings-in-c) – ProXicT Dec 07 '19 at 23:06

2 Answers2

0

The following snippet fix your error in sort function and use pointers:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sort(char ** s, unsigned int size) {

  for(unsigned int i=0 ; i<size ; i++) {
    for(unsigned int j=i+1 ; j<size ; j++) {
      if(strcmp(s[i],s[j])>0) {
        char aux[100];
        strcpy(aux,s[i]);
        strcpy(s[i],s[j]);
        strcpy(s[j],aux);
      }
    }
  }

}

int main() {

  unsigned int string_number = 3;
  unsigned int string_max_size = 100;
  char ** s = (char **) malloc(string_number*sizeof(char*));

  for(unsigned int i=0 ; i<string_number ; i++) {
    s[i] = (char*) malloc(string_max_size*sizeof(char));
    scanf("%s", s[i]);
  }

  sort(s, string_number);

  for(unsigned int i=0 ; i<string_number ; i++) {
      for(unsigned int i=0 ; i<string_number ; i++) {
      printf("%s\n", s[i]);
      free(s[i]);
  }

  free(s);

  return 0;

}
begarco
  • 751
  • 7
  • 20
-1
void sort(int *s)
{
    for(int i=0;i<n;i++)
        for(int j=i+1;j<n;j++)
           if(strcmp(s + i,s+j)>0)
           {
               char aux[100];
               strcpy(aux,s+i);
               strcpy(s+i,s+j);
               strcpy(s+i,aux);
           }


}
int main()
{
    char s[3][100];

    for(int i=0;i<3;i++)
      scanf("%s",s+i);

    sort(s);


    return 0;
}

Anyway, there is a bug in your program:

strcpy(aux,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],s[i]);

should be:

strcpy(aux,s[i]);
strcpy(s[i],s[j]);
strcpy(s[j],aux);
VillageTech
  • 1,968
  • 8
  • 18