簡體   English   中英

如何從void *轉換回int

[英]How do I convert from void * back to int

如果我有

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,並且你的意思是設置長d的args0 [1],你已經存儲了一個指向args0 [0]的指針和一個指向args0 [1]中b的指針。 這意味着您需要將它們轉換為正確的指針類型。

int c = *((int *)args0[0]);
int d = *((long *)args0[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;

試試這個:

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

雖然其他人已經回答了您的問題,但我會對您的代碼段的第一部分中的最后三行做出評論:

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指針之間的轉換,因此在最后兩個語句中不需要強制轉換。

如果您正在測試,我建議使用它作為外部函數,以獲得更多可讀性:

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

這應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM