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;
}
1

2 Answers 2

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;

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

Comments

-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);

Comments

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.