What do you mean by that?
Anyway, thanks! It worked! I don't know clearly why it worked, can you give me any reference?
Much obliged!!! |
It's a little bit hard to explain without pictures and all but I'll try
it's the value of the pointer that's being copied, the other pointer in the main function is not effected
let's say you have this code:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void test(int* b) {
b= new int(10);
std::cout << *b<< std::endl;
}
int main()
{
int* a = new int(5);
test(a);
std::cout << *a << std::endl;
return 0;
}
|
so you have a pointer in main which you pass to the function test.
The thing that's being passed is the value the pointer holds.
Therefore it's the same like this
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
int* a = new int(5);
int* b = a; // both point to the same location
b = new int(10); // a is not effected by that!!! a still points to the other integer
std::cout << *b << std::endl; // 10
std::cout << *a << std::endl; // 5
return 0;
}
|
with the function, the parameter b is just an other pointer pointing to the same location as the pointer in your main function, but when doing new, the pointer in main isn't changed, only the local pointer is modified
if you take the reference of the pointer then you modify the pointer itself, you don't make a copy of the pointer and then modify the new pointer.
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
int* a = new int(5);
int*& b = a; // b is now a reference to the int* a
b = new int(10); // a is effected by that because b modifies the object it's referencing
std::cout << *b << std::endl; // 10
std::cout << *a << std::endl; // 10
return 0;
}
|
or
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
void func(int*& b) {
b = new int(10);
std::cout << *b << std::endl;
}
int main()
{
int* a = new int(5);
func(a);
std::cout << *a << std::endl; // 10
return 0;
}
|