qsort: invalid conversion from ‘int’ to ‘__compar_fn_t

Feb 23, 2019 at 4:56pm
Hi all,

So I'm working through the book "Think like a programmer", and I'm having trouble with the qsort example. I'm receiving the error:

1
2
error: invalid conversion from ‘int’ to ‘__compar_fn_t {aka int (*)(const void*, const void*)}’ 
[-fpermissive] qsort(intArr, ARR_SIZE, sizeof(int), compareFunc);


My code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <stdlib.h>
using std::cin;
using std::cout;

int compareFunc(int, int);

int main() {
	const int ARR_SIZE = 10;
	int intArr[ARR_SIZE] = {87, 28, 100, 78, 84, 98, 75, 70, 81, 68};
	qsort(intArr, ARR_SIZE, sizeof(int), compareFunc);
	return 0;
};

// Comparator function for qsort
int compareFunc(const void * voidA, const void * voidB) {
	int * intA = (int *)(voidA);
	int * intB = (int *)(voidB);
	return *intA - *intB;
};


I think the error lies in the compareFuncation declaration, as the parameters are expected to be ints, yet within the function definition, they're expected to be void pointers. Is this accurate? Can someone shed some light on where my misunderstanding is?

Thank you!
Last edited on Feb 23, 2019 at 5:02pm
Feb 23, 2019 at 6:14pm
Your function declaration on line 6 should match that in its definition on line 16.

You also need some output.
Feb 23, 2019 at 6:35pm
Why not use std::sort since you're using C++? (Okay, the book is telling you to use qsort)

Here's your code C++'ified:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;

bool compareFunc(int, int);

int main() {
	const int ARR_SIZE = 10;
	int intArr[ARR_SIZE] = {87, 28, 100, 78, 84, 98, 75, 70, 81, 68};
	std::sort(intArr, intArr + ARR_SIZE, compareFunc);
	return 0;
};

// Comparator function for sort
bool compareFunc(int a, int b) {
    return a < b;
};


I suggest getting a book that teaches you C++ and not a weird frankenstein of the two.
https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
Last edited on Feb 23, 2019 at 6:40pm
Feb 23, 2019 at 8:12pm
Ok, it makes sense now.

Thank you both!
Topic archived. No new replies allowed.