I have to write a program that uses qsort and function pointers to sort an array of integers.
Write a program that sorts an array of n integers. After reading n and the values of the array from the standard input, the program reads a character and if this character is ’a’ then the sorting should be ascending, if the character is ’d’ then the sorting should be descending and if the character is ’e’ then the program should quit execution.
Here is my code, I keep getting the error: assignment of function 'void qsort(void*, size_t, size_t, int (*)(const void*, const void*))
. Could I please have some feedback? Am I approaching it completely wrong or should I just change a couple of things?
#include <ctype.h>
#include <stdlib.h>
void quicksort(int *a, int n, int (*func)(char c))
{
qsort = (a, n, sizeof(int), func);
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
}
int compare(char c)
{
if (c == 'a')
return -1;
if (c == 'd')
return 1;
else
return 0;
}
int main()
{
int *a, n, i;
scanf("%d", &n);
a = (int *)malloc(sizeof(int) * n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
char c;
while (1)
{
scanf("%c", c);
if (c == 'e')
break;
quicksort(a, n, compare);
}
free(a);
return 0;
}
qsort = (a, n, sizeof(int), func);
that tries to assign a value toqsort
. You are supposed to call the function not change it.compare
function signature is wrong. Read the qsort manual for what it needs to be. That is, your use ofqsort
is not correct. You need to write a compare function that compares two integers and not to compare against fixed values ofa
andd
.