如何从void *转换回int

时间:2010-07-08 02:22:31

标签: c

如果我有

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;

如何将args [0]和args0 [1]转换回int和long? 例如

int c=(something im missing)args0[0]
long d=(something im missing)args1[0]

6 个答案:

答案 0 :(得分:16)

假设你的& a0和& b0应该是& a和& b,并且你的意思是args0 [1]来设置长d,你已经存储了一个指向args0 [0]的指针]和指向args0 [1]中b的指针。这意味着您需要将它们转换为正确的指针类型。

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

答案 1 :(得分:2)

要字面回答你的问题,你要写

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

我可能会对您的代码感到担心的是,您已为指针分配了空间,但您还没有为本身分配内存。如果您希望将这些位置保留在本地范围之外,则必须执行以下操作:

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;

答案 2 :(得分:0)

试试这个:

 int c =  *( (int *)  args0[0]);

 long d = *( (long *) args0[1]);

答案 3 :(得分:0)

你需要告诉它,当你取消引用时,void *应该被解释为int *或long *。

int a = 5;
long b = 10;
void *args[2];
args[0] = &a;
args[1] = &b;

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

答案 4 :(得分:0)

虽然其他人已经回答了您的问题,但我会对您的代码段的第一部分中的最后三行做出评论:

args0 = (void **)malloc(count0 * sizeof(void *));
args0[0] = (void *)&a;
args0[1] = (void *)&b;

以上写得更好:

args0 = malloc(count0 * sizeof *args0);
args0[0] = &a;
args0[1] = &b;

malloc()调用更容易以这种方式阅读,并且不易出错。您不需要在最后两个语句中使用强制转换,因为C保证与对象指针和void指针之间的转换。

答案 5 :(得分:0)

如果您正在测试,我建议将其用作外部功能,以提高可读性:

int get_int(void* value){
    return *((int*) value);
}

long get_long(void* value){
    return *((long*) value);
}

然后在你的代码中:

 int c =  get_int(args0[0]);

 long d = get_long(args0[1]);

这应该有效。