utab said:
YYweii wrote:
Hi all
my teacher say there is something wrong with this piece of code,
but i can't figure it out, help !
void GetMemory(char *p, int num)
{
p = new char[num];
}
int main()
{
char *p;
GetMemory(p, 100);
...
...
}
Parameters in C and C++ are passed by value. The p inside of
GetMemory is different than the p inside of main. Whatever p
contained is copied to the local variable p in the subroutine. Any
changes made to p in GetMemory, therefore, are only visible to the p
in GetMemory. You need access to the pointer itself to change the
pointer.
Pointers are always a bit difficult to understand for me. I have a
question on this:
p is a pointer to a char in which p contains an address, right?
Yes. In main p is uninitialized, but lets say you unitiliazed it to NULL.
In main, then main's p would be 0x0000
And that address will be used to be the start address of the char
array, this is also right I guess. But the function is using a pointer
to a char as its parameter so passing an address should be ok. is not
passing p right conceptually, in main?
Now, you pass p from main to your function. Your function then gets passed
the value 0x0000. So now the p in your function contains the same address
as the p in main.
And in the function, p is char * so the new operator as well returns a
pointer to a char.
Correct. Lets say that new returned the address 0x1234. So the p in your
function is changed to 0x1234. Notice, however, that the value was copied
to the function. The p in main still contains 0x0000
Or I mixed everything desperately
?
When the function exits the local variable p gets deleted. So even though
it's pointing to 0x1234, nothing is done with that value, it's not seen in
main since just the value of p was passed to the function..