Why does my pointer to pointer program keep crashing? Shouldn't I be able to point to another pointer? This pointer stuff is so damn confusing, despite the fact I've deleted both variables. In this case, the value of "a" should point to the value of "b;" b itself should be equal to another variable.
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main()
{
int **b, *a;
**b=*a;
*a=4;
cout<<**b;
delete a;
delete b;
return 0;
}
Why does my pointer to pointer program keep crashing?
Because you delete memory you never allocated.
This pointer stuff is so damn confusing,
Yes, certainly pointers are difficult so don't use them. In modern C++ you can do without them. The STL has vectors, list, set, map so better learn to use them.
Thank you for the responses and the program above. I'm really having a hard time figuring out when to use the "*" and the "&" symbol. The below program (right below the paragraph) works, but I can't figure out why? Normally don't you have to use a "*" in order to get a variable equal to a value (eg. *a=b)? I think it's because you can't physically set a pointer directly to the value in another pointer.
#include <iostream>
int main()
{
int **a, *b;
a=&b;
*b=4;
cout<<**a;
return 0;
}
The below doesn't work though. The program should put the variable of A=B=C. I thought adding a normal variable c would fix the problem. I can normally set *A=another variable.
#include <iostream>
int main()
{
int **a, *b, c;
**a=*b;
*b=c;
c=3;
cout<<**a;
return 0;
}
The below program works, but I can't figure out why?
No, it does not. What you have is undefined behaviour. Too bad it deceptively seems to work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
int* * a; // The a is a pointer that is not set to point to anywhere
int* b; // The b is a pointer that is not set to point to anywhere
a = &b; // The a now points to b
*b = 4; // value 4 is assigned to the integer that the b points to #error1
cout << **a; // by deferencing a (*a) we reach the object the a points to (b)
// the b is pointer, so by deferencing it (**a) we reach the object the b points to
// #error2
return 0;
}
#error1 is fatal: you write to some unknown memory location. Anything could happen due to that.
#error2 simple attempts to read from unknown memory location. That happens to be the same memory, where you did previously write integer 4.
How to fix that? For example:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main()
{
int foo; // real integer
int* b = &foo;
int** a = &b;
*b = 4; // value 4 is assigned to foo
cout << **a; // value is read from foo
return 0;
}