r/AskComputerScience • u/[deleted] • Jul 16 '16
Can someone explain pointers to me?
I get that it stores the memory address of a variable, and by manipulating the address, you can manipulate the variable. The address is notated by &variable. However, some of the notations when the pointers are used to initialize arrays confuse me a lot. Can someone explain to me (or give me some internet resources) so i can understand pointers relating to arrays better?
Edit: This is all in C, BTW
3
u/Madsy9 Jul 16 '16
What C-beginners often find confusing is the multiple different uses for the star '*'. Skipping multiplication (obvious), it's both used for dereferencing pointers and to define/declare a pointer type as opposed to a normal non-pointer variable.
For example:
volatile int* SOME_MEM_BASE = 0x08000000;..is a definition of a pointer to int. While
*SOME_MEM_BASE = 0;..dereferences the pointer we made and sets the memory it points to, to zero. These are two different uses of *, so don't confuse the two.
Regarding pointers vs arrays, the difference is not that important in practice. The main difference is that arrays such as int foo[4] know their own size, while pointers don't know anything about the "length" of the data sequence they point to, or even if the memory address they point to is valid. As such, if you have data structures with a small upper bound on size or can pass constant-size arrays to functions, it can be a good idea for both readability and optimization. Compilers love to know the size of things.
But whatever you do, don't read about pointers-to-arrays aka int (*foo)[256] Your head will implode.
2
u/final-getsuga Jul 16 '16
You need pointers about pointers? https://xkcd.com/138/
1
u/xkcd_transcriber Jul 16 '16
Title: Pointers
Title-text: Every computer, at the unreachable memory address 0x-1, stores a secret. I found it, and it is that all humans ar-- SEGMENTATION FAULT.
Stats: This comic has been referenced 121 times, representing 0.1023% of referenced xkcds.
xkcd.com | xkcd sub | Problems/Bugs? | Statistics | Stop Replying | Delete
2
u/daV1980 Jul 16 '16
Others have given great answers, but let me give an analogy. Imagine that you are at the library. There are tons of books everywhere. In this analogy the books are memory (or RAM). In this analogy then, pointers are cards in the card catalog. They tell you a little bit of information about the book they point at (the type, the location) but in order to get more you need to go see the book itself.
3
u/riotinferno Jul 16 '16
Welcome to pointers! For the first 6 months of my professional career, I had a post-it on my monitor with pointer notation in it. It can be confusing.
int foo; //variable that stores a 32-bit value.
int *pFoo; // also int* pFoo; or int * pFoo; variable that stores a pointer.
pFoo = &foo; // & gets the memory address of the variable foo.
foo = *pFoo: // using the asterisk outside of the declaration gets the value of the memory address.
struct foo_s { int bar1; int bar2; };
foo_s* pStuff;
pStuff->bar1: // -> is the pointer equivalent of the 'dot'
foo_s stuff;
stuff.bar2;
Clear as mud?
2
u/argh523 Jul 16 '16 edited Jul 16 '16
&foo
pFoo = &foo; // & gets the memory address of the variable foo.
Seems to work, no escaping required. Why are you (double!) amp'ing?
1
u/riotinferno Jul 17 '16
I don't follow. Those aren't escapes, they're code comments.
2
u/argh523 Jul 17 '16
No not the comments, the "&". In your source you have
pFoo = &foo; // & ...which displays as
pFoo = &foo; // & ...
but it works fine with no escaping at all
pFoo = &foo; // & ...pFoo = &foo; // & ...
2
u/riotinferno Jul 18 '16
Thanks for pointing that out. I had submitted the comment on mobile, and apparently it added the & It didn't show up for me until I viewed it on the web browser. Strange!
1
1
u/lordvadr Jul 16 '16
Imagine you have a filing cabinet...or, well, two thousand filing cabinets. How do you tell someone where the car insurance is? You tell them, "cabinet 16, drawer 2." But then you have a problem where once drawer 2 is opened, where in the drawer is the car insurance? You and I can recognize what car insurance looks like, but, say a robot can't. So you go through all your filing cabinets and you then tape a measuring tape to each drawer so that you can say, "cabinet 16, drawer 2, 16cm."
This is a usable mechanism but it has some limitations. Not all files are 1cm thick. Sometimes you'll have files 10 times as big, sometimes you'll have files that are only a half cm thick. So you decide that whomever whats to use your filing system has to use it in 1cm widths. If they want to store 4 files in that cm, that's fine but it's up to them to figure it out when the filing cabinet robot grabs the whole cm. Or, if they want to store a file 10cm thick, you make them tell the filing cabinet robot "cabinet 16, drawer 2, location 4, and 5, and 6 and 7 and 8.... and 13." And it's up to them to figure out what is what.
This is a working example of how physical memory is managed in a modern computer. It's mostly the memory mamangement unit's (MMU's) job to handle the cabinet (DIMM) and drawer (chip) management.
So take it one step further, you simply say 160410 to mean cabinet 16, drawer 4, slot 10. This is the filing cabinet robot's job (the MMU's job). 160410 is what's called an address. People like to use your home address as an analogy, but I find that analogy lacking.
The filingcabinet robot doesn't care what's there, or what it means, you just say "160410" and you get what's at 160410. It could be car insurance, death star plans, or the number of beers in the fridge. The robot doesn't care.
Imagine trying to look through a filing cabinet with no labels on the files. You can't say, "find me the car insurance"...actually you can, but think of it more basically. If you say a=4, what are you going to ask the robot to do? "Fine me '4'?" There are millions of "4"'s in memory at any given time. You can't ask the robot for "4".
So when you name a variable, all your doing is asking the compiler to find a location in memory and be consistent with it. When you say a=4; the compiler spits out 160410 = 4 (not really, its a bit more complicated than that, but that's the jist of it.
When you say c=a*3, the compiler says "give me what's at 160410, multiply it by 3 and store that result into 160414 (or wherever it decided to put c)".
So the compiler handles the name<->address problem for you. It's one of the things that a compiler does, or at least what a higher level language does. But the CPU only cares about addresses.
In C, you get the address of a variable with the &. &a means the Address of a. You don't generally care what that address is...in fact, if you do, you're doing something wrong.
But, sometimes, you call a function and instead of it telling you "4", it tells you "here's where you can find the answer." Now, where do you store that? You store that in a pointer. A pointer stores the address of a memory location. A pointer literally tells you, go find what you're looking for at cabinet 16, drawer 4, slot 16. One of the poor designs in C is pointers and addresses because the language was written to expose some of the underlying aspects of the CPU to you...and in cases like drivers and such, you HAVE to have pointers. But it causes a lot of confusion in some places.
So the fist place people get confused, and one of the biggest confusions is scanf. You see, when you pass a variable in C, it passes its value. If you want some function to change your copy of a, you have to pass the address of a, hence why you have to say scanf("%d", &a)..you have to tell scanf where in your filing cabinet a lives. You have to give it the address of a.
The next thing that confuses people is scanf("%s", string) and the reason that this is confusing is that when you declare string[32], referencing the variable string is already a pointer. All arrays are pointers--again, a bit of a poor design in C.
The reason pointers are ambiguous is that they are simply integers. While it's not straight forward where the data will live (that's the MMU's job), pointers are simply addresses...like 160410...where the data lives.
So when you don't know what the address is ahead of time, you use a pointer, and then you ask the os/library/whatever "give me a memory location I can store this in." That's the reason malloc returns a pointer. You've said, "hey, filing cabinet robot, find me an empty slot Xcm wide." And it does. You then have to tell the compiler "I don't mean '4' i mean what's at address "4". That's where the asterisk comes in.
This response has dragged out far longer than I intended it to. If this doesn't explain it well, ask. PM me if you need to.
1
u/CobaltBlue Jul 16 '16
when i was TA-ing i often suggested students who were struggling with the concept watch this video for the basics before coming to me with specific questions if they still had any (this was for classes after the ones where they should have already learned this)
his teaching style is very accessible :) https://youtu.be/Rxvv9krECNw
27
u/PastyPilgrim Jul 16 '16 edited Jul 23 '16
I actually had a hard time understanding pointers until I learned assembly and how hardware works. For me at least, learning why we need/use pointers was the missing link in understanding them.
Your CPU has two* (simplified) places to store information: registers and memory (RAM/cache). Registers are where all the magic happens; they're tiny (e.g. 32 bits) memory cells that are used to perform work. Memory is comparatively massive and is where all of your data goes to wait until it's time to perform work on it (at which point it is loaded into a register). However, most data (arrays, strings, etc.) that you use will be a lot bigger than the size of your register.
This is where pointers come into play. A pointer is just an address that tells you where in memory you're working. Say I want to instantiate and use the string "hello world". For simplicity, let's say that we have 8 bit/1 byte registers and each character is 8 bits in size. In memory, Im going to allocate 11 bytes for my string and 1 byte for a null character (so I know where the string ends). The memory manager finds 12 bytes of free space and gives me the address of the start of that memory; let's say... the 100th byte. Now I'm going to load my 12 bytes into addresses 100 through 111. I can't do anything with that whole string because it's much bigger than my 8 bit registers, so in order to do things with my string, I'll need to just save that address, which is 8 bits in size (it's 1100100).
Now I have a "pointer" to the start of my string. If I use indexing in my string, all that's happening is that you're adding your index to the pointer address. So str[3] is telling C to load the fourth byte from address 100, and the byte at address 103 gets loaded from memory into a register for you to play with.
In C, when you use the asterisk as part of a variable definition (e.g.
int* x), you're telling it to reserve the space to store a pointer to a piece of data that is of type integer. When you don't use an asterisk, you're telling it to reserve the space to store an integer. If I wanted to create an array of integers, I would useint* xbecause that is going to create for me an address to the start of my array. This is where malloc and such come into place, because they are used to actually allocate the memory that you need for your array and return for you a pointer to the start of that memory. Soint* x = malloc(10)is asking malloc to reserve 10 bytes and assign the start of the memory tox.Now, whenever I use
x, that's going to be the address of the start of my array, not anything in the array itself. However, I can usex[3]to access the fourth integer in my array. Or I can use*xto dereference the pointer and load whatever byte is being addressed.So, what you might see sometimes is that, when looping through an array, I will change
xand just keep dereferencing it. At the start,xpoints to the first integer in my array. I do something with it using*x, then I sayx++so that x is now the address of the second integer in my array. I do something with it using*x, then I increment it to get to the third integer.What might be confusing is when you start getting into deeper pointers, like
char** foo, which you might see a lot in C. In that case, you have a pointer to a char pointer. Or, put another way, you have an address to an address to a character. Well, why would anyone ever want to have an address to an address? It's primarily so that a function can change the data without breaking other code.Let's say that my main calls a function that appends a character to the end of a string. My function is going to need to allocate memory equal to the current size of the string plus 1. And, with a pointer to a pointer, I can change where the start of my string is without needing to change that outer pointer. So A -> B -> the first character in my string. I can change B's address to point to a new string without affecting any other code that is going to use A to access my string.
That's pointers in a nutshell. Feel free to ask any questions.