casting a void pointer to an int.

Hi guys,

so I thought I casted a void pointer to an int the right way,but obviously not, so first I converted the ints to void pointers in sortAcsending,

once the function was called I then casted the ints to int pointers and dereferenced the values but the program just crashes

I was almost certain I was casting correctly

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
39
40
41
42
43
44
45
46
47
48
49
 #include <iostream>
#include <stdlib.h>

using namespace std;


int sortAcsending(const void* x,const void* y){


   int a ,b;
   cout << "HERE" << endl;

   a = *(int*) x; // crash occurs here
   b = *(int*) y; // crash occurs here

   cout << "a " << a << endl; // for debug
   cout << "b " << b << endl; // for debug

   if(a > b){

      return 1;
   }
   if(a == b){

      return 0;
   }
   else{

      return -1;
   }

}


int main()
{


    int arr[] = {5,9,3,6};

    int x = 7;
    int y = 6;

    sortAcsending((void*) (x),(void*)(y)); // when commented out qsort also 
    crashes 

    qsort(arr,4,sizeof(int),sortAcsending);

}



*EDIT

to solve it I passed in int pointers converted them to void pointers and everything worked fine,so to expand on my question how come I couldn't just cast the int to a void pointer then in the function convert it back to an int??

is there an easier way of doing this,instead of having an intermediary step of passing in int pointers,ie just passing in ints and converting them to void pointers like in my first code snippet? (edit*, talking to myself here but yes there is I should have used the address of operator instead of just passing an int)

sortAcsending((void*)&x,(void*)&y);


thanks

1
2
3
4
5
6
7
8
9
10

int x = 7;
    int y = 6;

    int* one = &x;
    int* two = &y;

    sortAcsending((void*)one,(void*)two);

    qsort(arr,4,sizeof(int),sortAcsending);
Last edited on
Why are you using qsort() in a C++ program, when there are better alternatives?
http://www.cplusplus.com/reference/algorithm/sort/

The C qsort() function in cstdlib necessarily accepts two void* pointers, which necessitates some casting in a C++ program.

C permits cast-less T* -> void* -> T* assignments.
C++ with it's tighter rules does not.
Topic archived. No new replies allowed.