<aside> <img src="/icons/home_green.svg" alt="/icons/home_green.svg" width="40px" />

Back to Home

</aside>

https://jennychen9827sbu.github.io/CAD281/pointers.html


What Is a Pointer?

A pointer in C is a variable that stores the memory address of another variable.

For example:

int a = 10;
int *p = &a;  // p is a pointer to int, storing the address of a


Why / When Use Pointers?

Use pointers to:

  1. Pass by reference to functions (modify variables in place)
  2. Dynamic memory allocation (malloc, calloc, etc.)
  3. Work with arrays and strings (they're basically pointers)
  4. Optimize performance (no copy of large structures)

1. Basic Pointer Declaration and Dereferencing

#include <stdio.h>

int main() {
    int num = 5;
    int *ptr = &num;

    printf("Value of num: %d\n", num);
    printf("Address of num: %p\n", &num);
    printf("Pointer ptr stores: %p\n", ptr);
    printf("Value at pointer ptr: %d\n", *ptr);

    return 0;
}

Here, *ptr accesses the value stored at the memory address held by ptr.