Pointers
Pointers
You learned from the previous chapter, that we can get the memory address
of a variable with the reference operator &:
#include <stdio.h>
Int main() {
Printf(“%d\n”, myAge);
Printf(“%p\n”, &myAge);
Return 0;
A pointer variable points to a data type (like int) of the same type, and is
created with the * operator.
The address of the variable you are working with is assigned to the pointer:
#include <stdio.h>
Int main() {
Int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the
address of myAge
Printf(“%d\n”, myAge);
// Output the memory address of myAge (0x7ffe5367e044)
Printf(“%p\n”, &myAge);
Printf(“%p\n”, ptr);
Return 0;
Example explained
Create a pointer variable with the name ptr, that points to an int variable
(myAge). Note that the type of the pointer has to match the type of the
variable you’re working with (int in our example).
Use the & operator to store the memory address of the myAge variable, and
assign it to the pointer.
Dereference
In the example above, we used the pointer variable to get the memory
address of a variable (used together with the & reference operator).
You can also get the value of the variable the pointer points to, by using the *
operator (the dereference operator):
#include <stdio.h>
Int main() {
Int myAge = 43; // Variable declaration
Printf(“%p\n”, ptr);
Printf(“%d\n”, *ptr);
Return 0;
Example
#include <stdio.h>
Int main() {
Int I;
Printf(“%d\n”, myNumbers[i]);
}
Return 0;
Instead of printing the value of each array element, let’s print the memory
address of each array element:
Example
#include <stdio.h>
Int main() {
Int I;
Printf(“%p\n”, &myNumbers[i]);
Return 0;
Note that the last number of each of the elements’ memory address is
different, with an addition of 4.
#include <stdio.h>
Int main() {
Int myInt;
Printf(“%lu”, sizeof(myInt));
Return 0;
Ok, so what’s the relationship between pointers and arrays? Well, in C, the
name of an array, is actually a pointer to the first element of the array.
Confused? Let’s try to understand this better, and use our “memory address
example” above again.
The memory address of the first element is the same as the name of the
array:
#include <stdio.h>
Int main() {
Printf(“%p\n”, myNumbers);
Printf(“%p\n”, &myNumbers[0]);
Return 0;