19

如果我有

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]
4

6 回答 6

21

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

int c = *((int *)args0[0]);
int d = *((long *)args0[1]);
于 2010-07-08T02:29:00.497 回答
4

从字面上回答你的问题,你会写

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;
于 2010-07-08T02:34:52.510 回答
0

试试这个:

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

 long d = *( (long *) args0[1]);
于 2010-07-08T02:30:55.060 回答
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];
于 2010-07-08T02:32:33.763 回答
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 指针之间的转换。

于 2010-07-08T22:33:41.677 回答
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]);

那应该行得通。

于 2018-05-28T10:53:17.363 回答