Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Experts,

C++
#include "stdafx.h"
#include <Windows.h>
void Test(LPVOID lpvBuffer);
int _tmain(int argc, _TCHAR* argv[])
{
	DWORD dwCode1 = 0;
	Test(&dwCode1);
	return 0;
}


void Test(LPVOID lpvBuffer)
{
	DWORD code = 200;
	lpvBuffer = &code;
}


In the method Test(), i am assigning value 200 to the LPVOID parameter, But i always getting a value 0 in dwCode1. What is the problem with this code ?

-Satheesh
Posted
Updated 28-Dec-13 21:00pm
v2
Comments
Albert Holguin 29-Dec-13 17:28pm    
I noticed you tried to set the pointer to the address of "code" in your Test() function. Don't even try to do that... you're setting the address of a local variable to pass back, that's not a good idea, because it will cease to exist once the function returns.

1 solution

You are not assigning a value to the location where lpvBuffer points, but to the pointer itself.

And why did you use a pointer to void if you want to pass a DWORD as in/out parameter? Use a pointer to DWORD instead. So you code should look like this:
C++
void Test (DWORD* pArg)
{
	DWORD code = 200;
	*pArg = code;
}
 
Share this answer
 
Comments
Satheesh1546 29-Dec-13 4:43am    
Thank you ! How to assign a value to the location where lpvBuffer points with out changing the parameter to DWORD ?
nv3 29-Dec-13 5:05am    
In order for the comiler to know how large (and of which type) the location is that you want to write a value to, it must have a type. Hence you cannot assign a value via a void pointer. If that is all you have and you know that the pointer in fact points to a DWORD you can cast it, e.g.:

*((DWORD*) lpvBuffer) = code;

Using this technique without exactly knowing what you are doing will however get you in trouble and can produce errors that are extremely difficult to debug.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900