How To Access Memory Address In C
In C, there are several ways to access memory addresses or work with them. Here are the main methods:
1. Using the Address of Operator (&)
The & operator is the primary way to get the address of a variable in C. You can use it on variables to retrieve their memory addresses.
int x = 10; int *ptr = &x; // ptr now holds the address of x printf("Address of x: %p\n", &x);
Output
Address of x: 000000000061FE14
2. Using Pointers
Pointers are variables that store memory addresses. They allow indirect access to other variables’ values using their addresses.
int x = 10; int *ptr = &x; // Pointer to x printf("Address of x: %p\n", ptr); // Casting ptr to (void*) for portability return 0;
Output
Address of x: 000000000061FE14
3. Using Arrays
In C, array names act as pointers to their first elements. Accessing an array element’s address can be done using indexing or the & operator.
int arr[3] = {1, 2, 3}; printf("Address of first element: %p\n", (void*)&arr[0]);
Output
Address of first element: 000000000061FE14
4. Using malloc(), calloc(), or realloc()
These functions allocate memory dynamically and return a pointer to the allocated memory block.
int *ptr = malloc(5 * sizeof(int)); // Allocates memory for 5 integers if (ptr != NULL) { printf("Address of allocated memory: %p\n", (void*)ptr); // Corrected cast to (void*) } else { printf("Memory allocation failed.\n"); return 1; // Return an error code if memory allocation fails } free(ptr); // Free the memory when done
Output
Address of allocated memory: 0000000000761480
5. Using &(*pointer) Notation
Although redundant, you can use &(*pointer) to access the address of the variable that the pointer points to. It is equivalent to using just the pointer itself.
int x = 10; int *ptr = &x; printf("Address of x using &(*ptr): %p\n", &(*ptr));
Output
Address of x using &(*ptr): 000000000061FE14