问题描述
说我有一个void *命名PTR。我应该去究竟如何使用PTR来存储一个int?是否足以写
Say I have a void* named ptr. How exactly should I go about using ptr to store an int? Is it enough to write
ptr = (void *)5;
如果我要保存5号?还是我对malloc的东西保存?
If I want to save the number 5? Or do I have to malloc something to save it?
推荐答案
您正在铸造 5
是一个无效的指针的然后分配到 PTR
。
You're casting 5
to be a void pointer and assigning it to ptr
.
现在 ptr指向的内存地址0x5的
如果这实际上是你想要做什么..嗯,是啊,这工作。你......可能不希望这样做。
If that actually is what you're trying to do .. well, yeah, that works. You ... probably don't want to do that.
当你说存储一个int我会想你的意思是你想实际整型值5存储在内存指向的无效*
。只要有足够的分配内存(的sizeof(INT)
),你可以用铸造这样做...
When you say "store an int" I'm going to guess you mean you want to actually store the integer value 5 in the memory pointed to by the void*
. As long as there was enough memory allocated ( sizeof(int)
) you could do so with casting ...
void *ptr = malloc(sizeof(int));
*((int*)ptr) = 5;
printf("%d\n",*((int*)ptr));
这篇关于C编程:铸造一个空指针为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!