Your computer science professor has just asked you to write a program for him (he would do it himself but he's too busy grading your assignments). The program is supposed to read in all of his students' grades and then print them back out in sorted order. Simple, right? You grab your trusty bubble sort algorithm, write up a function to sort an array of data, then write a simple little program to read in all of the numbers, sort them, and print them back out, maybe something like:
There could be many reasons why your professor isn't happy with the code above. For example, there's not much in the way of error checking. More importantly though, he's probably a little wary of that 100 you have there in the code. You realize that, of course, he's got over 100 students in his class, so we'll just change this number to 500, allow him to have up to 500 students. You go home that night, again feeling very proud of yourself. The next year, though, you get a call from that professor again, and he's upset. Seems this year he had an influx of students and your program wasn't robust enough to handle all of them; you hadn't set aside enough memory and as such your program was of no more use to him. You think to yourself, "Back to the drawing board; there must be an easier way so that I don't have to keep rewriting this program every time the professor's class size changes." You're in luck, there is an easier way. Or at least a better one.
Up to this point, the memory we've been using has been static memory. What does this mean? Static memory is memory that is set aside automatically by the compiler for your program. When you declare a variable, such as the int arr array we declared in the above program, you're telling the computer to set aside space for 100 integers. The computer of course obliges. The problem with this is that the computer needs to know how much memory to set aside before your program starts running. When you run your program, the computer gives it the memory it needs to hold all of the variables you've declared; in other words, you've statically allocated memory.
But this method fails in the above case with the professor. What we'd like to be able to do is to create an array whose size is specified at run time. This time, the computer doesn't oblige; it fact, neither does the compiler. If you try to write code that looks like:
So, how do we get around this? The answer is dynamic memory allocation, and for that, we need pointers.
Dynamic memory allocation is a process that allows us to do exactly what we're looking to do above, to allocate memory while our program is running, as opposed to telling the computer exactly how much we'll need (and for what) ahead of time.