Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何从void*转换回int_C - Fatal编程技术网

C 如何从void*转换回int

C 如何从void*转换回int,c,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=(someth

如果我有

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]

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

int c = *((int *)args0[0]);
int d = *((long *)args0[1]);
试试这个:

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

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

您需要告诉它,当您取消引用时,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];

要真正回答你的问题,你可以写

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;

其他人已经回答了您的问题,我将对代码片段第一部分的最后三行进行评论:

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保证对象指针和空指针之间的转换。

如果您正在测试,我建议将其用作外部函数,以获得更高的可读性:

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]);

这应该行得通。

intc=*((int)args0[0]);原因错误:“一元*”(有“int”)和int c=((int*)args0[0])的类型参数无效;fprintf(stderr,“main():%d\n”,c);导致输出为-4261808I不明白。我的答案与顶部的答案(已被接受)有什么区别?当你第一次发布时,出于某种原因,“*”在“int”之后缺失,可能是因为它被解释为格式——请参阅w31的注释了解它的外观。作为旁注,我认为将
void*
转换为
int
long
是不好的做法。在给定的平台上,整数和指针的宽度不一定相同。一种更方便的方法是使用
intptr\u t
或者更好的
uintpr\u t
。这保证了你不会散开碎片。