Accessing Memory Address
Lesson 26Author : Afrixi
Last Updated : January, 2023
In C, you can access the memory address of a variable using the ampersand (&) operator. The memory address is also known as a pointer.
Here’s an example:
#include <stdio.h>
int main() {
int num = 42;
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num); // %p format specifier is used to print memory address
return 0;
}
Output:
Value of num: 42
Address of num: 0x7ffee224177c
In the example, we declare an integer variable num
and assign it a value of 42
. We then print the value of num and its memory address using the printf()
function. The %p format specifier is used to print the memory address.
We can also declare a pointer variable and assign it the memory address of another variable using the asterisk (*
) operator. Here’s an example:
#include <stdio.h>
int main() {
int num = 42;
int *ptr = #
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);
printf("Value of ptr: %p\n", ptr);
printf("Value at address pointed by ptr: %d\n", *ptr);
return 0;
}
Output:
Value of num: 42
Address of num: 0x7ffee224177c
Value of ptr: 0x7ffee224177c
Value at address pointed by ptr: 42
In the example, we declare a pointer variable ptr
that points to the memory address of num
. We then print the value of num
, the memory address of num, the value of ptr
, and the value at the memory address pointed by ptr
. We use the asterisk (*
) operator to access the value at the memory address pointed by ptr
. This is known as dereferencing the pointer.