4 ms·
Every piece of data lives somewhere in memory. A pointer is a piece of data containing the address of another piece of data. int a = 42; // puts the number 42
by somethingsimple 9y ago
Every piece of data lives somewhere in memory. A pointer is a piece of data containing the address of another piece of data.
int a = 42; // puts the number 42 somewhere in memory
int* p = &a; // gives you the address where that 42 is stored
A function with a signature like
int f(int n);
takes an int as an argument. When you pass it the a above, it is copied in the stack before the function is called. If you change n inside the function, that only affects the value of n inside the function. But let's say you wanted to change what was passed in to it. In that case you would change f to
int f(int* p);
Now when you pass the a declared above (using &a) you actually have a pointer to a in f i.e. the address where a is stored. If you do
*p = 51;
inside f, you changed the value of a and that change is visible even after f returns.
Hope that helps.