如果我有一个空指针,我怎么把一个int成吗? [英] If I have a void pointer, how do I put an int into it?
问题描述
我有任意值的数组,所以我把它定义为空指针数组,所以我可以指向任何类型的信息(如 INT
,性格阵列等)。然而,实际上,我怎么分配 INT
呢?
就拿这些初始化:
void *的数据[10];
INT X = 100;
我的直觉会想到这一点,但是这给编译错误:
数据[0] =的malloc(sizeof的(INT));
*(数据[0])= X;
我也想过用&放大器; X
,但我会采取的局部变量,它(我的理解)将在程序退出后清除的地址。所以,如果我有一个局部变量 X
,我怎么会让它变成一个空指针的变量类型是否正确?
*((INT *)数据[0])= X;
将做到这一点。
您可能要考虑使用一个联盟。事情是这样的:
工会myvalues
{
INT I;
双D;
长升;
};
然后,您可以有
工会myvalues * foo的[10];
富[0] =的malloc(sizeof的(工会myvalues));
富[0] - I标记= X;
您也可以的typedef
工会。 的sizeof(工会myvalues)
将sizeof的成员的最大的。所以,如果你有
INT I;
和字符C [40]
在工会,的sizeof (联合myvalues)
将40写入 I
然后将覆盖第4角色C
(假设你的int为4个字节)。
I have an array of arbitrary values, so I have defined it as an array of void pointers, so I can point to any kind of information (like int
, character arrays, etc). However, how do I actually assign an int
to it?
Take for example these initializations:
void* data[10];
int x = 100;
My intuition would think this, but this gives a compile error:
data[0] = malloc(sizeof(int));
*(data[0]) = x;
Also I thought about using &x
, but I would take the address of a local variable, which (to my understanding) would be cleared after exiting from the procedure. So if I have a local variable x
, how would I get it into a void pointer type of variable correctly?
*((int*)data[0])=x;
will do it.
You might want to consider using a union. Something like this:
union myvalues
{
int i;
double d;
long l;
};
You could then have
union myvalues *foo[10];
foo[0] = malloc(sizeof(union myvalues));
foo[0]->i = x;
You can also typedef
the union. sizeof(union myvalues)
will be the maximum of sizeof
the members. So if you have int i;
and char c[40]
in the union, sizeof(union myvalues)
will be 40. Writing to i
will then overwrite the first 4 characters in c
(assuming your ints are 4 bytes).
这篇关于如果我有一个空指针,我怎么把一个int成吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!