1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
int main(){ // <- must be int main(), never void main()
int *p, x=10; // <- creates a pointer 'p' and a regular int 'x'
p=&x; // <- p now "points to" x
cout<<*p<<endl; // <- this prints the contents of whatever p points to. Since p points to x,
// this will print the contents of x, which is 10
// so far... all of that is OK
int *q=p; // <- OK this makes a new pointer q which is a copy of p. IE: it points to the same thing
// p points to (which is x)
cout<<*q<<endl; // <- so since q points to x, this will print "10" because x still contains 10
int **r=&p; // <- r is a pointer to a pointer to an int. Here, r points to p
cout<<"r"<<r<<endl; // <- this will print the contents of r (which is an address). So this is like printing &p
cout<<"*r"<<*r<<endl; // <- this prints the contents of whatever r points to
// since r points to p, and p contains an address, this also prints an address
// here, we are printing the address of x. so: &x
cout<<"**r"<<**r<<endl;// <- this dereferences twice, which takes whatever r points to... then takes whatever
// THAT points to and prints it. So since *r is p, and *p is x... **r is x. So this will print 10
// Here's where it gets crummy:
int *d= new int; // <- this creates a new "unnamed" variable in memory. Let's call this variable "foo".
// Our 'd' pointer is pointing to foo.
d=*r; // <- this makes d point to SOMETHING ELSE (specifically, x). So now 'foo' is no longer being pointed to
// IE: it is a memory leak. It has no name, and isn't being pointed to, so it is impossible to access.
cout<<*d<<endl; // <- this prints whatever d points to. Since d points to x, and x is 10, this prints 10
d=0; // <- this makes it so d points to nothing
delete d; // <- this attempts to delete whatever d points to, but since d points to nothing... it does nothing
cout<<d<<endl;
// You PROBABLY meant to do this:
{
int *d = new int; // <- create "foo", d points to foo
*d = x; // <- assign x (10) to whatever d points to. Since d points to foo, this is like doing
// foo = x;
cout << *d << endl; // prints foo, which is 10
delete d; // <- deletes whatever d points to ... which is foo. So this eliminates the memory used by foo.
// here, 'foo' no longer exists
// since 'd' still points to foo, but foo no longer exists.. this means 'd' is now a BAD POINTER
d = 0; // <- make d point to nothing (null) so it's clear that it's a bad pointer.
}
// Continuing on....
*d = **r; // <- this is attempting to dereference r twice (giving you 'x') and assign that value to whatever
// d points to. BUT 'd' POINTS TO NOTHING BECAUSE YOU JUST SET IT TO A NULL POINTER
// therefore this will typically cause a crash.
| |