Segmentation fault

What's wrong with my code? Getting segmentation fault when trying to compile:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <stdlib.h>   
#include <stdio.h>


int values[] = { 40, 10, 100, 90, 20, 25 };


int compare(const void *s1, const void *s2)
{
	
	long l1, l2;
	char *endptr;
	
	const char *p1 = *(const char**) s1;
	const char *p2 = *(const char**) s2;
	
	l1 = strtol(p1, &endptr, 10);
	l2 = strtol(p2, &endptr, 10);
	
	return (l1-l2);
		
}




int main ()
{
  int n;
  qsort (values, 6, sizeof(int), compare);
  for (n = 0; n < 6; n++)
     printf ("%d ",values[n]);
  return 0;
}


Since you pass an array of ints to qsort you can and should cast it to an *int.

1
2
3
4
5
6
7
8
9
10
int compare(const void *s1, const void *s2)
{
	
	int *p1 = (int *) s1;
	int *p2 = (int *) s2;
	
	return (*p1 - *p2);
		
}
Topic archived. No new replies allowed.