Accessing a variable through its pointer involves dereferencing the pointer, which means accessing the value stored at the memory address pointed to by the pointer.
Here’s how you can access a variable through its pointer in C:
#include <stdio.h>
int main()
{
int x = 10; // Define an integer variable ‘x’
int *ptr = &x; // Define a pointer ‘ptr’ and initialize it with the address of ‘x’
// Accessing the value of ‘x’ through its pointer ‘ptr’
printf(“Value of x: %d\n”, *ptr);
return 0;
}
In this example:
- We define an integer variable x and initialize it with the value 10.
- We define a pointer variable ptr and initialize it with the address of the variable x using the “address-of” operator (&).
- To access the value of x through its pointer ptr, we use the dereference operator (*ptr). This retrieves the value stored at the memory address pointed to by ptr.
- We then print the value of x using *ptr.
When you run this program, it will print the value of x, which is 10, obtained through its pointer ptr.
It’s important to note that dereferencing a pointer when it’s not pointing to a valid memory address (e.g., when it’s uninitialized or pointing to NULL) leads to undefined behavior, which may result in a segmentation fault or other runtime errors. Always ensure that the pointer is properly initialized and points to a valid memory location before dereferencing it.