C:C Pointers: Memory Addresses, Dereferencing (*), and Pointer Arithmetic
C•Pointers

C Pointers: Memory Addresses, Dereferencing (*), and Pointer Arithmetic

Pointers store raw memory addresses, enabling direct hardware manipulation and efficient buffer management in C.

Syntax

int* ptr = &variable; *ptr = 100;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&Address-of OperatorReturns memory address of a variable.
*Dereference OperatorReads or modifies value at stored memory address.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

#include <stdio.h>

// Simulating pass-by-reference using pointers
void swap(int* x, int* y) {
    int temp = *x;
    *x = *y;
    *y = temp;
}

int main(void) {
    int a = 15;
    int b = 95;

    printf("Before swap: a = %d, b = %d\n", a, b);
    swap(&a, &b);
    printf("After swap:  a = %d, b = %d\n\n", a, b);

    // Pointer arithmetic over an array
    int numbers[] = {10, 20, 30};
    int* p = numbers; // points to first element

    printf("Value at *p:     %d\n", *p);
    printf("Value at *(p+1): %d\n", *(p + 1));
    printf("Value at *(p+2): %d\n", *(p + 2));

    return 0;
}
Expected Output:
Before swap: a = 15, b = 95
After swap:  a = 95, b = 15

Value at *p:     10
Value at *(p+1): 20
Value at *(p+2): 30

How It Works: Step-by-Step

  • Lines 4-8: swap function dereferences pointers to swap values in caller stack.
  • Line 15: Calls swap(&a, &b) passing memory addresses of a and b.
  • Lines 19-25: Pointer arithmetic *(p + 1) advances pointer by sizeof(int) bytes.

Key Concepts

  • Pointers hold memory addresses; *ptr reads or writes the value stored at that address.
  • Pointer arithmetic automatically scales offsets by sizeof(type).
  • NULL is used to represent a pointer that points to nothing.

Common Mistake: Dereferencing an uninitialized or NULL pointer

Dereferencing NULL or wild pointers immediately causes Segmentation Fault (core dumped).

❌ Incorrect
int* p; *p = 50; // Undefined Behavior: writes to random memory!
✅ Correct
int val = 0; int* p = &val; *p = 50; // Safe

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler