0

I've been trying to write a function to sort an array of char pointers and print them out. Using the qsort function, but for some reason, I can't seem to be able to sort them in the output. The inputs are basically an array of MAC addresses in the format:

84:1b:5e:a8:bf:7c

74:e2:f5:17:96:89

00:8e:f2:c0:13:cc

74:e2:f5:17:96:89

I've looked around and tried different functions of for the string compare section and other examples of qsort, but I still can't get it to work. My code is:

int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));
}


void countDistinct(char* MAClist[], int n){
char* bufList[n];
for(int i = 0; i < n; i++){
    printf("success1 ");
    bufList[i] = str_dup(MAClist[i]);
    printf("success2 ");
    printf("%s \n", bufList[i]);
    printf("success \n");
}

qsort(bufList, n, sizeof(*bufList), compare_function);
for(int j = 0; j < n; j++){
    printf("%s \n", bufList[j]);
}

}

The reason why I'm trying to sort it is so that I can count the number of distinct objects efficiently. But the sorting has to be done again at a later stage anyway, so I'll need to reuse the function. Any help is appreciated!

1
  • 2
    Try return (strcmp((char *)a,(char *)b)); --> return (strcmp(*(char **)a,*(char **)b)); Commented Sep 10, 2017 at 16:16

1 Answer 1

2

Need to fix your compare function like following :

int compare_function(const void * a, const void * b ) {
    // a, b are pointer to const char*, when passed from qsort 
    const char *pa = *(const char**)a;
    const char *pb = *(const char**)b;

    return strcmp(pa,pb);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.