pointer help
-
I have the following codes: void Fun(int *v1, int *v2); int *n1 = 0; int main(int argc, char* argv[]) { int *n2 = new int; *n2 = 3; Fun(n1, n2); delete n2; return 0; } void Fun(int *v1, int *v2) { v1 = v2; } After compiled and run, the value of n1 is supposed to the pointer value of v2 which contains an integer 3 after called Fun and before the delete statement. But actually not, n1 is still 0 after called Fun. why? Thanks.
-
I have the following codes: void Fun(int *v1, int *v2); int *n1 = 0; int main(int argc, char* argv[]) { int *n2 = new int; *n2 = 3; Fun(n1, n2); delete n2; return 0; } void Fun(int *v1, int *v2) { v1 = v2; } After compiled and run, the value of n1 is supposed to the pointer value of v2 which contains an integer 3 after called Fun and before the delete statement. But actually not, n1 is still 0 after called Fun. why? Thanks.
Thats is because if you pass an argument as pointer then only changes in the value of the argument will be preserved. If you want to change the pointer itself then you have to use double poitner.
int *n1 = 0;
void Fun(int **v1, int *v2)
{
*v1 = v2;
}int main(int argc, char *argv[])
{
int *n2 = new int;
*n2 = 3;Fun(&n1, n2); // n1 and n2 both point to same memory location here. delete n2; return 0;
}
-Saurabh