简体   繁体   English

使用指针对c中的字符串数组进行排序

[英]Sorting an array of strings in c using pointers

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

The following snippet fix your error in sort function and use pointers:以下代码段修复了sort函数中的错误并使用指针:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM