0
0
Cprogramming~5 mins

Why pointers are needed in C

Choose your learning style9 modes available
Introduction

Pointers let you work directly with memory addresses. They help you change data in one place and see the change everywhere else.

When you want to change a variable inside a function and keep the change after the function ends.
When you want to work with large data without copying it, like big arrays or structures.
When you need to create dynamic data that can grow or shrink while the program runs.
When you want to build complex data structures like linked lists or trees.
When you want to share data between different parts of a program efficiently.
Syntax
C
type *pointerName;

// Example:
int *p;

The asterisk (*) means the variable is a pointer.

Pointers store the address of another variable, not the value itself.

Examples
Here, p points to x. Using *p lets you access or change x.
C
int x = 10;
int *p = &x;  // p holds the address of x
A pointer to a character variable.
C
char c = 'A';
char *pc = &c;
Array name acts like a pointer to its first element.
C
int arr[3] = {1, 2, 3};
int *pa = arr;  // points to first element
Sample Program

This program shows how a pointer lets a function change a variable outside its own scope.

C
#include <stdio.h>

void changeValue(int *p) {
    *p = 20;  // change value at address p points to
}

int main() {
    int a = 10;
    printf("Before: %d\n", a);
    changeValue(&a);  // pass address of a
    printf("After: %d\n", a);
    return 0;
}
OutputSuccess
Important Notes

Always initialize pointers before using them to avoid errors.

Using pointers can make programs faster and use less memory.

Be careful with pointers to avoid mistakes like accessing invalid memory.

Summary

Pointers store addresses of variables.

They let functions change variables outside their own scope.

Pointers help manage memory efficiently and build complex data structures.