Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert from void * back to int in C

Tags:

c

if I have

int a= 5;
long b= 10;
int count0 = 2;
void ** args0;
args0 = (void **)malloc(count0 * sizeof(void *));
args0[0] = (void *)&a;
args0[1] = (void *)&b;

how can I convert from args[0] and args0[1] back to int and long? for example

int c=(something im missing)args0[0]
long d=(something im missing)args1[0]
like image 596
w31 Avatar asked Jul 08 '10 02:07

w31


2 Answers

Assuming that your &a0 and &b0 are supposed to be &a and &b, and that you mean args0[1] for setting up long d, you have stored a pointer to a in args0[0] and a pointer to b in args0[1]. This means you need to convert them to the correct pointer types.

int c = *((int *)args0[0]);
int d = *((long *)args0[1]);
like image 96
Arthur Shipkowski Avatar answered Oct 28 '22 12:10

Arthur Shipkowski


To literally answer your question, you'd write

int c = *((int *)args0[0]);
long d = *((long *)args[1]);

What might concern me about your code is that you have allocated space for the pointers to your locations, but you haven't allocated memory for the values themselves. If you expect to persist these locations beyond the local scope, you have to do something like:

int *al = malloc(sizeof(int));
long *bl = malloc(sizeof(long));
*al = a;
*bl = b;
void **args0 = malloc(2 * sizeof(void *));
args0[0] = al;
args0[1] = bl;
like image 30
keithm Avatar answered Oct 28 '22 13:10

keithm