This blog post will cover the basics of pointers, a programming tool that is used in languages like C and C++. In this post, we will be using C as our primary language. Pointers are variables that contain a memory address (a concept used to access the computer’s primary storage memory). Variables normally contain a value such as 1 or ‘a’, but pointers contain an address of the value. When we reference a variable through pointers, this is called indirection. Each link goes to a text file of C code. This code can be run as is and will help show us the power of pointers!
The “&” (ampersand) operator is the address operator, using the ampersand will return the address of a variable.
The “*” (asterisk) operator is a pointer to a variable.
Using pointers allows us to pass variables into functions, and then manipulate the values of these variables inside the function, and have them persist after the function is out of scope. Without pointers, this is impossible!
Pointers are powerful! To finish this blog post, we will see how pointers can be used to sort an array of numbers with the bubble sort function (a type of sorting algorithm).
Bubblesort Code
With pointers, we can change the entire array in bubblesort, and these changes will remain persistent even after the bubblesort function is no longer in scope!
I have a question. Does the variable that you intend to change need to be the same name for both where you initially create it and where you change it?
For example, in your bubblesort code, you initialize your array inside of your main function and call it “array”, and inside your bubblesort function you have it written so that it is expecting to receive an integer called “array” which you will then be looking at the computer address of (thanks to that *).
Could you have instead written it so that when you created the bubblesort it says that it is expecting to receive “whateverIWantToGiveIt” instead?
Thanks,
James
When you declare a function, you can absolutely have a different name!
If you change the declaration from int bubblesort(int *array) to int bubblesort(int *anewname), you can run this code after you change all instances of “array” in the bubblesort function to “anewname”.
I hope this helps!
-Josh