C Pointers
Creating Pointers
C pointers are a fundamental and powerful concept in C programming. They are variables that store memory addresses of other variables, functions, or even other pointers. By understanding pointers, you unlock a whole new level of flexibility and control over your code.
Example
#include <stdio.h>
int main() {
int myAge = 42;
printf("%d\n", myAge);
printf("%p\n", &myAge);
return 0;
}Output
42
0x7ffe5367e044
Pointers are declared using the asterisk (*) symbol after the data type
To assign the address of a variable to a pointer, use the address-of operator (&)
To access the value stored at the memory location pointed to by a pointer, use the dereference operator (*):
Example
#include <stdio.h>
int main() {
int myAge = 43;
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge
// Output the value of myAge (43)
printf("%d\n", myAge);
// Output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", &myAge);
// Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
return 0;
}
Output
43
0x7ffe5367e044
0x7ffe5367e044
Example explained
Create a pointer variable called ptr, which points to an int variable (myAge). Note that the type of the pointer must match the type of the variable you are working with (int in our example).
Use the & operator to store the memory address of the myAge variable, and assign it to the pointer.
Now, ptr holds the value of myAge's memory address.
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):
Example
#include <stdio.h>
int main() {
int myAge = 43; // Variable declaration
int* ptr = &myAge; ; // Pointer declaration
// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
// Dereference: Output the value of myAge with the pointer (43)
printf("%d\n", *ptr);
return 0;
}
Output
0x7ffe5367e044
43
Note that the * sign can be confusing here, as it does two different things in our code:
When used in declaration (int* ptr), it creates a pointer variable.
When not used in declaration, it act as a dereference operator.
Good To Know: There are two ways to declare pointer variables in C:
Note:int* myNum;
int *myNum;
Notes on Pointers
Pointers are one of the things that make C stand out from other programming languages, like Python and Java.
Pointers and Memory Manipulation:But be careful; pointers must be handled with care, since it is possible to damage data stored in other memory addresses.