From the preceding chapter, you discovered that the memory address of a variable can be obtained using the reference operator & :
int myAge = 43; // an int variable printf(“%d”, myAge); // Outputs the value of myAge (43) printf(“%p”, &myAge); // Outputs the memory address of myAge (0x7ffe5367e044) |
A pointer is a variable that holds the memory address of another variable as its value.
A pointer variable references a data type (such as int) of matching kind and is established using the * operator.
The pointer is assigned the memory address of the variable you are working with.
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) // Output the memory address of myAge with the pointer (0x7ffe5367e044) |
Declare a pointer variable named ptr, which references an integer variable (myAge). Ensure that the type of the pointer corresponds to the type of the variable being referenced (int in this example).
Utilize the & operator to obtain the memory address of the myAge variable, then assign this address to the pointer.
At this point, ptr contains the memory address of myAge.
In the example provided, we utilized the pointer variable to obtain the memory address of another variable, employing the & reference operator.
The value of the variable referenced by the pointer can also be accessed using the * operator, known as the dereference operator.
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) |
It’s worth noting that the * sign serves two distinct purposes in our code:
Certainly: In C, pointer variables can be declared in two different ways. |
int* myNum; int *myNum; |
Notes on Pointers Certainly: Pointers are a distinctive feature of C, setting it apart from other programming languages such as Python and Java. They play a crucial role in C programming by enabling manipulation of data stored in a computer’s memory. This capability not only streamlines code but also enhances performance. For those acquainted with data structures like lists, trees, and graphs, pointers prove particularly valuable for their implementation. Additionally, pointers become indispensable in certain scenarios, such as file operations and memory management tasks. Absolutely, caution is warranted when dealing with pointers, as mishandling them can potentially corrupt data stored in other memory addresses. |