|
-
February 19th, 2012, 12:56 AM
#7
Re: Simple question - mem addresses
For me I find working code helps me understand what the book is telling us. Sometimes the books IMO, just don't allow me to visualize it well so I have to take some time and create a small program. Although not perfect it did help me understand pointers when we learning that 4 weeks ago but did not use again for a few weeks. Makes it hard to retain when you do not use it alot or keep building on it.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int *p;
int q=5;
p = &q;
cout << "The program is doing this:\n";
cout <<"int *p;\n";
cout <<"int q=5;\n";
cout <<"p = &q;\n";
cout << setfill('-')<<setw(25) << "-\n";
cout <<"So when we run a few things here is what happens:\n";
cout << "Value of int q is: " << q <<endl;
cout << setfill('-')<<setw(25) << "-\n";
cout << "Mem. address of q by doing '&q' but not really useful.\n";
cout << "q is a variable, not a pointer.\n";
cout << "q address is: "<< &q <<endl;
cout << setfill('-')<<setw(25) << "-\n";
cout << "p is: " << p << " the address the pointer p is pointing to, the address of q.\n";
cout << "&p is: " << &p << " the address the p by doing &p.\n";
cout << "*p is pointing to q so when using *p we get the value of q: " << *p <<endl;
delete p;
cout << setfill('-')<<setw(25) << "-\n";
cout << "After 'delete p;' and doing 'cout p' the output of p is now: " << p << " the mem. address of p"<< endl;
cout <<"On my system the pointer p is still showing the memory space it was pointing to."<<endl;
cout << setfill('-')<<setw(25) << "-\n";
cout <<"Now to do it better we set the pointer to NULL after the \n";
cout <<"delete opertion with 'p= NULL;'."<<endl;
p = NULL;
cout << "After 'delete p; p=NULL;' the output of p is now: " << p <<endl;
cout <<"The mem. address that p is pointing to which does not exist. Hence is its zero"<< endl;
return 0;
}
Does make sense or am I completely wrong here?
That could be my problem if I am using this as my guide and why I would have troubles.
Last edited by mm12463; February 19th, 2012 at 12:58 AM.
Reason: spelling
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|