I haven't programmed in awhile and I have seemed to atrophied any knowledge on structuring a program. I apologize. I'm doing some problems in the back of my old C++ book, and I entered this to what I remember standard C++ structuring of a program is:
--------------------
#include <iostream>
using namespace std;
--------------------
I believe I'm missing crucial pieces to complete the operations of the program, especially while using Pointers. I'm really confused on how to structure the program. If anyone could give me a little boost with my personal project I would really appreciate it!
I'm given:
---
1 2 3 4 5 6 7 8 9 10
int x;
int y;
int *p = &x;
int *q = &y;
x = 35;
y = 46;
p = q;
*p = 78;
cout << x << " " << y << endl;
cout << *p << " " << *q << endl;
---
I've structured it like this:
----
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main ()
{
int *p;
int *q;
p = newint;
q = p;
*p = 46;
*q = 39;
cout << *p << " " << *q << endl;
return 0;
}
---
I know I'm missing a lot -- I've read the chapter relating to Pointers. But I believe I am missing significant background information to structure this program effectively.
I'm not clear on what exactly is the problem. However, the two code segments you posted are different.
The first one.
Line 3 declares a pointer p and makes it point to the location of x. So x and *p are the same memory location.
Line 4 declares a pointer q and makes it point to the location of y. So y and *q are the same memory location.
Line 7 assigned p, the address in q. So y, *q and *p are the same memory location.
Line 8 assigned 78 to *p, so y, *q and *p have the value 78.
The second one.
Line 6 and 7 declare pointers p and q. They are uninitialised and can point anywhere.
Line 9 allocated an int on the heap and stores it's address in p. p points to an unnamed variable.
Line 10 assigns q the value of p, so p and q point to the same value on the heap.
Line 11 assigns that value on the heap, 46.
Line 12 assigns that value on the heap, 39.
The program terminates without releasing the allocated int back to the heap.