C Memory Addresses and Pointers

Memory Addresses

Every variable in C is stored at a memory address. You can find that address using the & operator.

Loading...
Output:

Pointer Basics

A pointer is a variable that holds the memory address of another variable. A pointer is declared with *

Loading...
Output:

Pointer Declaration and Initialization

To declare a pointer: int *ptr;

To assign it the address of a variable: ptr = &x;

Loading...
Output:

Dereferencing

Dereferencing a pointer means accessing the value at the memory location it points to. Use *ptr to do this.

Loading...
Output:

Pointer Reassignment

Pointers can be reassigned to point to different variables, as long as types match.

Loading...
Output:

Printing Pointer Addresses

Use %p with printf() to print pointer addresses.

Loading...
Output:

p vs. *p

  • p holds the memory address to which it is assigned to
  • *p points to the content that is held in the memory address which it is assigned to

Changing Values Using Pointers

You can use pointers to modify a variable's value by referencing its memory address. This is useful for updating values inside functions or performing direct memory manipulation.

  • *ptr is used to dereference the pointer and access/change the value.
  • &var is used to get the address of a variable.
Loading...
Output:

Practice Question

What will this print?

A. Address of x
B. 10
C. Error
int x = 10;
int *ptr = &x;
printf("%d", *ptr);

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic