4 ms·
Pointers
by thdn 9y ago
Pointers
- somethingsimple 9y agoEvery 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.
- imwally 9y agoA pointer is a value. That value is a memory location. That memory location should contain a value too. The value the pointer points to. Pointers start to make more sense when you take the comment above about pass by value vs. pass by reference into consideration. There's a great gif about this where a cup is used as the argument to a fillCup() function. https://blog.penjee.com/wp-content/uploads/2015/02/pass-by-reference-vs-pass-by-value-animation.gif https://blog.penjee.com/wp-content/uploads/2015/02/pass-by-r... In pass by value, a second cup is created just for that function and then filled with liquid. The original cup is left untouched. With pass by reference, the original cup is being filled, not a duplicate of it. How does the function know to fill the original instead of creating a duplicate for its own scope? A pointer. When calling a function with arguments a few things are happening behind the scenes. Memory allocation for these arguments is one of those things. This is where the stack and heap come into play. Memory allocated for the function call is considered the stack while memory for the entire program (think global variables) is the heap. Things get even more interesting when you look into stack frames and step through the execution of a program with a debugger like gdb or lldb. You'll start to understand how recursion works. Pointers are also used in certain data structures like a linked list. They allow you to easily keep a chain of values that contain data and a pointer which points to the next data, otherwise known as a linked list, or binary tree, or many other names depending on the structure. I'm replying on my phone so I apologize in advanced for the formatting. Hope this helps.