### Pointers as function parameters.

Hi, need some clarification if my understanding of this is right.

 ``1234567891011121314151617181920`` ``````#include using std::cin; using std::cout; using std::endl; void test (int *x) { *x = 5; } int main() { int y; cin >> y; test(&y); cout << y << endl; return 0; }``````

The relationship between x and y, is it like *x = &y?
No, the relation between x and y is

x = &y;

because x has type int *. So it stores only addresses.

On the other hand there is a relation

*x = y;
Last edited on
Okay I don't get it now, can you please explain what is going on with the code?
It will be more easy to understand if to write simply without using any function

 ``123456789101112131415`` ``````#include int main() { int y; int *x = &y; std::cin >> y; std::cout << "y = " << y << ", *x = " << *x << std::endl; *x = 5; std::cout << "y = " << y << ", *x = " << *x << std::endl; }``````

EDIT: I updated some typo.:)
Last edited on
 Okay I don't get it now, can you please explain what is going on with the code?

May be I fail to see what you mean?
1. y is assign a value from standard input (cin).
2. Next y will be overwritten with the value 5 (test()).
3. Finally y will be written to standard output (cout).
Sorry I shouldn't have been so vague and actually explain. This is my thought process so far.

So y is assigned a value, then that value is used as an argument for pointer x.

`test(&(y)) //What I think y is getting treated as at the moment. `

In the function, pointer x gets dereference and is assigned the value of 5.

Since y is the address of pointer x, and when a pointer is dereferenced it is also accessing the object which it is pointing to, y is also assigned (overwritten) the value of 5 (what I understand about pointers, address and dereference from vlad's code).

Is that what's going on?
Last edited on
If you are speaking about my code then y is not an address. It is an object that gets its value after statement

std::cin >> y;

x is a pointer that is initialized by the address of object y. So after the declaration

int *x = &y;

x is equal to the address of y that is x == &y.

So y and *x is the same object. That means that after

*x = 5;

y is also equal to 5.

Last edited on
Alright cool. Just as a final clarification is that what's technically happening with the code I posted?
Exactly the same as in my code.
Awesome, that cleared up a lot. Thanks vlad you're really helpful =).
Topic archived. No new replies allowed.