Nano Technology

Pointers in C Programming


1. What is a Pointer?

A pointer in C is a variable that stores the memory address of another variable. Instead of holding a data value directly, a pointer holds the location where the data is stored.

Pointers provide direct access to memory and are one of the most powerful features of the C programming language.

Pointers in C ProgrammingC

2. Declaration of Pointers

Pointer declaration specifies the type of variable whose address the pointer can store.


data_type *pointer_name;

Example:


int *ptr;
float *fptr;

Here, ptr can store the address of an integer variable.

3. Initialization of Pointers

Pointer initialization means assigning the address of a variable to a pointer using the address-of operator (&).


int a = 10;
int *ptr = &a;

Now, ptr stores the address of variable a, and the value of a can be accessed using the dereference operator (*).

4. Pointer Arithmetic

Pointer arithmetic allows operations such as increment, decrement, addition, and subtraction to be performed on pointers.

When a pointer is incremented, it moves to the next memory location based on the size of the data type.


ptr++;   // moves to next integer location

Pointer arithmetic is commonly used in array traversal.

5. Pointers and Arrays

Arrays and pointers are closely related in C. The name of an array represents the address of its first element.


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

Using pointer notation, array elements can be accessed as:


*(p + 1)   // accesses second element

Pointers provide an efficient way to access and manipulate array elements.

6. Pointers and Functions

Pointers can be passed to functions to allow modification of actual arguments. This mechanism is known as call by reference.


void change(int *x)
{
    *x = 50;
}

Passing pointers to functions improves efficiency and enables functions to modify original data.

7. Advantages of Pointers

  • Efficient memory management
  • Supports dynamic memory allocation
  • Enables call by reference
  • Essential for arrays, strings, and structures
  • Used in low-level system programming

8. Examples

#include <stdio.h>
int main()
{
    int a = 10;
    int *ptr;

    ptr = &a;

    printf("Value of a = %d\n", a);
    printf("Address of a = %p\n", ptr);
    printf("Value using pointer = %d\n", *ptr);

    return 0;
}

This program demonstrates pointer declaration, initialization, and dereferencing.

9. Common Mistakes

  • Using uninitialized pointers
  • Dereferencing null pointers
  • Confusing * and & operators
  • Accessing memory outside array bounds
  • Memory leaks due to improper pointer usage
Note: A strong understanding of pointers is essential before learning dynamic memory allocation, file handling, and advanced data structures.