Pointer Problem

Hi guys, I'm having trouble with the program I'm trying to write. Here's what it says:

The following function uses reference variables as parameters. Rewrite the function so it uses pointers instead of reference variables, and then demonstrate the function in a complete program.

1
2
3
4
5
6
7
int doSomething(int &x, int &y)
{
    int temp = x;
    x = y * 10;
    y = temp * 10;
    return x + y;
}

Can anyone help me figure this out? I really appreciate it :) Thanks you guys.
Last edited on
Could you be more specific as to what you don't understand, or do you just need someone to do your homework for you?

Anyway, so that this reply not be devoid of a "real" answer, read on...

A pointer is a variable which holds a memory address to data.
You declare a pointer by using an asterisk instead of an ampersand.

Example: int *x;

When you wish to use the data that the pointer points to, you dereference it.
You use the asterisk. This can be confusing, because you also use it to declare the pointer.

Example: *x = 5;

How do you give a pointer a memory address?
You reference a regular variable. By using the ampersand.

Example:
1
2
3
4
int a; // regular variable
int *x; // pointer
x = &a; // get a's memory address
*x = 5; // change a to 5 


In your case, you need to declare x and y as pointers in your function's parameter list.
Then you need to dereference every time you change or use the data they're pointing to.
Finally when you call your doSomething() function, you need to reference the variables you pass to it: doSomething(&x, &y);

Good luck.
Topic archived. No new replies allowed.