Pointers in C

Subject: Data Structures and Algorithms · Language: C · Level: intermediate · 6 min read

Understand addresses, pointer variables, dereferencing, pointer arithmetic, and function updates.

A pointer is a variable that stores the address of another variable. Normal variables store values. Pointer variables store locations.

Pointers are one of the most important parts of C because they help a program work directly with memory. Arrays, strings, dynamic memory, linked lists, trees, and many system-level programs depend on pointers.

Address and Value

Every variable has two things: a value and an address.

& and * Operators

```c

int value = 25;

int *ptr = &value;

```

Here, `ptr` stores the address of `value`.

Pointer Declaration

A pointer is declared using `*` with a data type.

```c

int *p;

float *pricePtr;

char *namePtr;

```

The pointer type should match the type of value it points to. An `int *` pointer should normally store the address of an `int` variable.

Dereferencing

Dereferencing means accessing the value using a pointer.

```c

printf("%d", *ptr);

```

If `ptr` points to `value`, then `*ptr` gives the value stored in `value`.

Changing `*ptr` changes the original variable because the pointer is working on the same memory location.

Why Pointers Are Useful

Pointer and Function Connection

When you pass a normal variable to a function, the function usually receives a copy. When you pass its address, the function can update the original value.

This style is often called call by address. It is useful when a function needs to change more than one value.

```c

#include <stdio.h>

void swap(int *first, int *second) {

int temp = *first;

*first = *second;

*second = temp;

}

int main(void) {

int a, b;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

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

swap(&a, &b);

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

return 0;

}

```

Pointers and Arrays

An array name represents the address of its first element. That is why arrays and pointers are closely connected.

```c

int arr[3] = {10, 20, 30};

int *p = arr;

```

Here, `p` points to `arr[0]`. Then `*(p + 1)` gives the second element.

NULL Pointer

A pointer that does not currently point to a valid memory location should be set to `NULL`.

```c

int *ptr = NULL;

```

This makes the pointer safer because you can check it before using it.

Important Points

Pointer Safety

Pointers are powerful, but careless use can crash a program. Do not dereference a pointer if it is `NULL` or if it has not been assigned a valid address.

After freeing dynamic memory, many programmers set the pointer to `NULL` to avoid accidentally using old memory.

Practice Question

Write a C program that takes two numbers and uses pointers to find their sum and product.

More C Lessons

Browse all PrepCampus study materials