Not able to use the pointer to a dynamic allocated memory as a function parameter
-
Hi, (my first post on CodeProject :) ) I am unable to use GetPtrEx and GetPtrEx2 function versions. I get Unhandled exception. Please tell me why... class CTest { private: char *a; public: CTest(int n=10) { a= new char[10]; a="george"; } virtual ~CTest() { } char * GetPtr() { return a; } void GetPtrEx(char **ptOut) { ptOut=&a; } void GetPtrEx2(char *ptOut) { ptOut=a; } }; int _tmain(int argc, _TCHAR* argv[]) { CTest obj; char *rx=NULL; obj.GetPtrEx(&rx); cout<<"sir="<
-
Hi, (my first post on CodeProject :) ) I am unable to use GetPtrEx and GetPtrEx2 function versions. I get Unhandled exception. Please tell me why... class CTest { private: char *a; public: CTest(int n=10) { a= new char[10]; a="george"; } virtual ~CTest() { } char * GetPtr() { return a; } void GetPtrEx(char **ptOut) { ptOut=&a; } void GetPtrEx2(char *ptOut) { ptOut=a; } }; int _tmain(int argc, _TCHAR* argv[]) { CTest obj; char *rx=NULL; obj.GetPtrEx(&rx); cout<<"sir="<
The parameters need to be passed as references (e.g.,
void GetPtrEx2(char*& ptOut)
). As it is, you're making a local copy of the parameter in the function bodies and are manipulating that local copy. The variable in your main function is unchanged after calling GetPtrEx because only the local copy inside the accessor was modified. In order to have changes inside the accessor preserved and made available to the caller, the parameters must be passed as references. In effect, this passes the address of the original variable, rather than making a local copy. Changes made in the accessor will affect the original copy of the variable declared outside the accessor. Also, in the future, use the 'code block' button above the edit window when posting code. It makes it much more readable; a lot of people here won't even respond to a message loaded with unformatted code. ;) -
Hi, (my first post on CodeProject :) ) I am unable to use GetPtrEx and GetPtrEx2 function versions. I get Unhandled exception. Please tell me why... class CTest { private: char *a; public: CTest(int n=10) { a= new char[10]; a="george"; } virtual ~CTest() { } char * GetPtr() { return a; } void GetPtrEx(char **ptOut) { ptOut=&a; } void GetPtrEx2(char *ptOut) { ptOut=a; } }; int _tmain(int argc, _TCHAR* argv[]) { CTest obj; char *rx=NULL; obj.GetPtrEx(&rx); cout<<"sir="<
CTest(int n=10)
{
a = new char[10];
a = "george";
}This is incorrect, you are merely overwriting the pointer in a; you need to copy the string to 'a' via
strcpy()
or similar. Also the constructor takes a value that is never used.void GetPtrEx(char **ptOut)
{
ptOut = &a;
}This changes the local copy of ptOut; it should be
*ptOut = a;
. SimilarlyGetPtrEx2()
does nothing useful.