C Memory Address

1. What is a Memory Address?

  • Every variable in C is stored at a specific location in memory.

  • The memory address is the location where the variable’s value is stored.

  • You can find the address using the address-of operator &.


2. Address-of Operator &

  • The & operator returns the memory address of a variable.

Example:

#include <stdio.h>

int main() {
int num = 10;
printf(“Value of num: %d\n”, num);
printf(“Address of num: %p\n”, &num);
return 0;
}

Output (example):

Value of num: 10
Address of num: 0x7ffee3b2c8ac

%p is used to print pointer/memory addresses in a readable format.


3. Accessing Value Using Pointers

  • A pointer is a variable that stores the address of another variable.

#include <stdio.h>

int main() {
int num = 50;
int *ptr = &num; // ptr stores the address of num

printf(“Value of num: %d\n”, num);
printf(“Address of num: %p\n”, &num);
printf(“Value stored in ptr: %p\n”, ptr);
printf(“Value pointed by ptr: %d\n”, *ptr); // dereference pointer

return 0;
}

Output:

Value of num: 50
Address of num: 0x7ffee3b2c8ac
Value stored in ptr: 0x7ffee3b2c8ac
Value pointed by ptr: 50

*ptr gives the value stored at the address.


4. Memory Address of Array Elements

  • Each element of an array has a contiguous memory address.

#include <stdio.h>

int main() {
int numbers[5] = {10, 20, 30, 40, 50};

for (int i = 0; i < 5; i++) {
printf(“numbers[%d] = %d, Address = %p\n”, i, numbers[i], &numbers[i]);
}

return 0;
}

Output (example):

numbers[0] = 10, Address = 0x7ffee3b2c8a0
numbers[1] = 20, Address = 0x7ffee3b2c8a4
numbers[2] = 30, Address = 0x7ffee3b2c8a8
numbers[3] = 40, Address = 0x7ffee3b2c8ac
numbers[4] = 50, Address = 0x7ffee3b2c8b0

Notice each int usually occupies 4 bytes, so addresses increment by 4.


5. Key Points About Memory Addresses

  1. Use & to get the address of a variable.

  2. Use pointers to store and manipulate addresses.

  3. Array elements have contiguous addresses in memory.

  4. %p is used for printing addresses in pointer format.

  5. Understanding addresses is crucial for pointers, dynamic memory, and efficient programming.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *