NO

Author Topic: problem with qsort  (Read 1849 times)

tpekar

  • Guest
problem with qsort
« on: March 11, 2014, 04:28:37 PM »
Can someone tell me why the following console program does not sort the records using qsort?

#include <stdio.h>
#include <stdlib.h>
char names[5][10]={"tom","anna","tim","alicia","tonya"};
char **keys;
int i=0;
main(int argc, char *argv[]) {
int strcmp();
keys=malloc(sizeof(char *)*5);
for (i=0;i<5;i++) {
  keys=malloc(9);
  strcpy(keys,names);
}
qsort(keys,5,sizeof(char *),strcmp);
for (i=0;i<5;i++) printf("\n%s",keys);
}

Thanks in advance.

tpekar

  • Guest
Re: problem with qsort
« Reply #1 on: March 11, 2014, 04:39:32 PM »
I dug this up off the internet.  It seems to work.

#include <stdio.h>
#include <stdlib.h>
char names[5][10]={"tom","anna","tim","alicia","tonya"};
char **keys;
int i=0;
int compare(const void *arg1, const void *arg2);
main(int argc, char *argv[]) {
int strcmp();
keys=malloc(sizeof(char *)*6);
for (i=0;i<5;i++) {
  keys=malloc(9);
  strcpy(keys,names);
}
qsort(keys,5,sizeof(char *),compare);
for (i=0;i<5;i++) printf("%s\n",keys);
}

int compare(const void *arg1, const void *arg2) {
return strcmp(* (char**) arg1, * (char**) arg2);
}