Discussion Forums > Technology

Programming Help! (C++)

(1/2) > >>

TMRNetShark:
Hello everyone, I need some help getting a program started (not really written for me, but more of a guideline of how to set it up). Here are the instructions..

(click to show/hide)1) Declare an integer x and initialize x to 5.
2) Declare a pointer to an integer px and initialize px to the address of x.
3) Use the pointer px to add 2 to x (indirect reference).  The value of x should now be 7.
4) Use the pointer px to display the value of x (indirect reference).
 
In steps 3 and 4 above, make sure your program uses the pointer px (indirect reference) rather than using the integer x (direct reference).
I do not know how to set up or do 3-4 to work properly. Any help would be great!

Garret02:
I think it should be like this

--- Code: ---
int x = 5;
int *px;
px = &x;
*px += 2;
cout<<*px<<endl;
--- End code ---

TMRNetShark:

--- Quote from: Garret02 on May 04, 2011, 09:17:58 PM ---I think it should be like this

--- Code: ---
int x = 5;
int *px;
px = &x;
*px += 2;
cout<<*px<<endl;
--- End code ---

--- End quote ---

Now I can use this all under main, correct? No global variables or other functions, correct?

Garret02:
Yup, but remember to use either std:: before every cout and cin or type "using namespace std;" outside any function.

Freedom Kira:
That's pretty much right, though I would use

--- Code: ---
int *px = &x;

--- End code ---
instead of

--- Code: ---
int *px;
px = &x;

--- End code ---
because I'm lazy. And you should be, too. Save yourself as much typing as possible - it'll decrease the chance of bugs.

And you can put this code anywhere, though parts 3 and 4 won't work so well in the global domain.

The "using namespace std;" should come once in every .cpp file below all your includes (unsure of exact include syntax because different languages use different include syntax). For example:

--- Code: ---
#include iostream
using namespace std;

int main(void)
...

void function1(char x)
...

--- End code ---

And for beginner-level C++, you should be putting the "using namespace std;" in pretty much every .cpp file.

Navigation

[0] Message Index

[#] Next page

Go to full version