基本指针用法
我正在尝试编写一个函数,它接受一个指向 int 的 void 指针,然后将 int 加倍,并将其放回内存位置:
void doubleNumber(void *number){
number = &((*((int*)(number))) * 2);
}
所以首先我将它从 void * 转换为 int *,然后我尊重 int * 得到该值,然后乘以 2,然后得到该值的地址并将其放回指针中。
谁能告诉我为什么我的逻辑不起作用?
谢谢
I'm trying to write a function that takes a void pointer to an int and then doubles the int, and puts it back into the memory location:
void doubleNumber(void *number){
number = &((*((int*)(number))) * 2);
}
So first I cast it into an int * from a void *, then I deference the int * to get the value, then I multiply by 2 and then I get the address of that to put it back into the pointer.
Can anyone give me tips on why my logic is not working?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会这样写:
首先将
number
转换为int*
类型。然后取消引用指针。然后加倍。您的代码的问题是您正在分配指针而不是受指点。
I'd write it like this:
First of all cast
number
to be of typeint*
. Then dereference the pointer. Then double it.The problem with your code is that you are assigning the pointer rather than the pointee.
步骤 1:
步骤 2:
Step 1:
Step 2:
首先,C 中函数的参数是按值传递的,因此修改
number
不会产生任何效果。其次,即使确实如此,您也应该首先为该值分配一些内存。只有这样你才能返回一个指向内存中这个地方的指针。
Firstly, arguments to functions in C are passed by value, so modification of
number
will have no effect.Secondly, even if it did, you should allocate some memory for the value first. Only then can you return a pointer to this place in memory.
值(例如 2)没有地址。
相反,只需写:
或者更短:
A value (such as 2) has no address.
Instead, simply write:
or, shorter: