为什么传递给函数的指针值没有变化? [英] Why does not the value of the pointer passed to the function change?
问题描述
我将指针作为参数传递给函数.在函数内部,我对其进行了更改->它已更改.但是之后的输出与函数调用之前的输出相同.指针没有改变.怎么了?
I pass the pointer as a parameter to the function. Inside the function I change it -> it has changed. But after the output is the same as before the function call. The pointer has not changed. What's wrong?
void GetFrom(PVOID lpBuffer){
lpBuffer = malloc(12);
memset(lpBuffer, 0, 12);
printf("%p",pointer); // 0000028D46DECE50
}
PVOID pointer = 0x0;
printf("%p",pointer); // 000000C2628FEFE4
GetFromMap(pointer);
printf("%p",pointer); // 000000C2628FEFE4
在调试中,我看到指针的值在函数内部发生了变化.
In debugging, I saw that the value of the pointer changed inside the function.
推荐答案
请注意,lpBuffer = malloc(12)
只是更改了局部变量lpBuffer
的值,但这对已传递给GetFrom
的变量没有影响. .要更改调用方变量中指针的值,您需要将指针传递给该指针.
Note that lpBuffer = malloc(12)
just changes the value of local variable lpBuffer
, but this has no effect to the variable which's value has been passed to GetFrom
. To change the value of the pointer in the caller`s variable, you need to pass a pointer to that pointer.
void GetFrom(PVOID *lpBuffer){
*lpBuffer = malloc(12);
memset(*lpBuffer, 0, 12);
printf("%p",*lpBuffer); // !=0x0
}
PVOID pointer = 0x0;
GetFromMap(&pointer);
printf("%p",pointer); // should be != 0x0
BTW:您可以使用calloc
代替malloc
和后续的memset to 0
,它使用0
-
BTW: instead of malloc
and a subsequent memset to 0
, you could use calloc
, which implicitly fills the allocated memory with 0
-
这篇关于为什么传递给函数的指针值没有变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!