Back to C Programming
2025-12-136 min read

14 Pointers (C Programming)

Learn 14 Pointers (C Programming) step by step with clear examples and exercises.

Title: 14 Pointers (C Programming) - A full guide for Practical Depth

Why This Matters

In C programming, pointers are a fundamental data type that allows you to manipulate memory directly, providing more control over your programs. They are essential for tasks like dynamic memory allocation, function arguments, and complex data structures. Understanding pointers can help you write efficient code, solve real-world bugs, and prepare for interviews.

Prerequisites

Before diving into pointers, ensure you have a solid understanding of the following concepts:

  1. Basic C syntax (variables, operators, control structures)
  2. Arrays
  3. Functions
  4. File I/O
  5. Understanding memory allocation and deallocation in C
  6. Knowledge of data types and their sizes
  7. Familiarity with the concept of memory address and how it works in C

Core Concept

What is a Pointer?

A pointer in C is a variable that stores the memory address of another variable. It allows you to access and manipulate data stored at different memory locations.

int num = 10; // num is an integer variable storing the value 10
int *ptr; // ptr is a pointer variable that can store the memory address of an integer
ptr = # // Assign the memory address of num to ptr

In this example, ptr now points to the memory location where num is stored. You can access the value of num through ptr using the dereference operator (*).

Pointer Variables and Dereferencing

To declare a pointer variable, you use the asterisk (*) symbol before the variable name. To access the value that a pointer points to, you use the dereference operator (*) before the pointer variable.

int num = 10;
int *ptr = #
printf("%d", *ptr); // Output: 10

Pointer Arithmetic

You can perform arithmetic operations on pointers to move them between memory locations of the same data type. Incrementing (++) or decrementing (--) a pointer moves it to the next or previous memory location, respectively.

int arr[] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
printf("%d", *(ptr+1)); // Output: 2

Pointer Types and Sizes

C provides several pointer types like char*, int*, double*, etc. To find the size of a pointer, use the sizeof operator.

size_t size = sizeof(int*); // size now stores the size of an int pointer

Pointer Constants

You can declare pointers as constant using the const keyword. A constant pointer points to a memory location that cannot be changed, while a non-constant pointer can be used to change the value stored at its pointed location.

int num = 10;
const int *ptr = # // ptr is a constant pointer pointing to num
*ptr = 20; // Compile error: cannot assign to 'num' through 'ptr', which is a read-only variable

Worked Example

Let's create a simple program that declares an array of integers, initializes it with values, and then uses pointers to iterate through the array and print its elements.

#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4, 5};
int *ptr;

for(ptr = arr; ptr < arr + sizeof(arr) / sizeof(*arr); ++ptr) {
printf("%d ", *ptr);
}

return 0;
}

In this example, we use a for loop to iterate through the array using the pointer ptr. The loop continues until ptr points one past the last element in the array, as indicated by arr + sizeof(arr) / sizeof(*arr).

Common Mistakes

  1. Forgetting the dereference operator (*) when accessing the value a pointer points to.
int num = 10;
int *ptr = &num;
printf("%d", ptr); // Output: memory address, not the value of num
  1. Incorrectly using pointer arithmetic.
char str[] = "Hello, World!";
char *ptr = str;
printf("%s", ptr + 7); // Output: World, not an error, but it should have output !
  1. Not initializing pointers before using them.
int num = 10;
int *ptr;
printf("%d", *ptr); // Output: undefined behavior, as ptr is uninitialized
  1. Forgetting to free dynamically allocated memory when it's no longer needed.
int *arr = (int*) malloc(10 * sizeof(int));
// ... use the array ...
free(arr); // Forgetting this line can lead to a memory leak
  1. Using the incorrect dereference operator with pointer constants.
const int *ptr = &num;
*ptr = 20; // Compile error: cannot assign to 'num' through 'ptr', which is a read-only variable

Practice Questions

  1. Write a program that declares an array of 10 integers and uses pointers to find the sum of all even numbers in the array.
  2. Given two strings str1 and str2, write a function that compares them using pointers and returns their lexicographical order (e.g., "apple" < "banana").
  3. Write a program that dynamically allocates memory for an array of integers, initializes it with user input, and then uses pointers to find the maximum and minimum values in the array.
  4. Write a function that takes two pointers to integers as arguments and swaps their values without using a temporary variable.
  5. Implement a linked list data structure in C using pointers.
  6. Explain the difference between a pointer constant and a regular constant (e.g., int const num = 10).
  7. Write a function that takes a pointer to an integer as an argument, increments its value, and returns the new value without modifying the original variable.
  8. How can you check if two pointers point to the same memory location?
  9. What happens when you try to assign a float value to an int pointer?
  10. Write a program that uses pointers to implement a simple calculator with addition, subtraction, multiplication, and division operations.

FAQ

  1. Why do we need pointers in C?
  • Pointers provide more control over your programs by allowing direct manipulation of memory. They are essential for tasks like dynamic memory allocation, function arguments, and complex data structures.
  1. What is the difference between a pointer variable and a regular variable?
  • A pointer variable stores the memory address of another variable, while a regular variable stores its value directly.
  1. How do I check if a pointer is null or not in C?
  • You can use the NULL keyword or 0 to represent a null pointer. To check if a pointer is null, compare it with NULL or 0:
int *ptr = NULL;
if (ptr == NULL) {
printf("ptr is null\n");
}
  1. What happens when I assign an integer directly to a pointer variable?
  • Assigning an integer directly to a pointer variable results in undefined behavior, as the pointer will not point to a valid memory location.
  1. How can I find the memory address of a variable using a pointer?
  • You can use the & operator to get the memory address of a variable and assign it to a pointer:
int num = 10;
int *ptr = &num;
printf("%p", ptr); // Output: memory address of num
  1. What is a null pointer?
  • A null pointer is a special value that represents an uninitialized or invalid pointer. It can be represented by the NULL keyword in C, which expands to 0 (zero) when compiled.
  1. Can I compare pointers for equality?
  • Yes, you can compare pointers for equality if they point to the same memory location. However, comparing pointers with different data types or pointing to different memory locations will result in undefined behavior.
  1. What is pointer aliasing and why should I avoid it?
  • Pointer aliasing occurs when multiple pointers point to the same memory location. While C does not explicitly forbid aliasing, it can lead to hard-to-debug issues such as data corruption and unexpected program behavior. To avoid aliasing, ensure that each pointer points to a unique memory location or use appropriate synchronization mechanisms in concurrent programming.
  1. What is the purpose of the & operator in C?
  • The & operator in C returns the memory address of its operand. It is often used with pointers to assign the address of a variable to a pointer or to get the address of a specific element in an array.
  1. What is the purpose of the * operator in C?
  • The * operator in C is used for two purposes: dereferencing a pointer (accessing the value stored at the memory location pointed by the pointer) and multiplication (when used with numbers). In the context of pointers, it is primarily used for dereferencing.