• Home
  • Pointer Basics – Pointer Increment Operations

Pointer Basics – Pointer Increment Operations

View Categories

Pointer Basics – Pointer Increment Operations

< 1 min read

This example demonstrates how pointer arithmetic behaves differently for different data types. The amount by which a pointer moves depends on the size of the datatype it points to.



⚙️
main.c

Copy to clipboard

#include <stdio.h>

int main()
{
    int arr[] = {10, 20, 30};
    char ch[] = {'A', 'B', 'C'};

    int *iptr = arr;
    char *cptr = ch;

    printf("iptr      = %p\n", iptr);
    printf("iptr + 1  = %p\n", iptr + 1);

    printf("cptr      = %p\n", cptr);
    printf("cptr + 1  = %p\n", cptr + 1);

    printf("*iptr     = %d\n", *iptr);
    printf("*(iptr+1) = %d\n", *(iptr + 1));

    printf("*cptr     = %c\n", *cptr);
    printf("*(cptr+1) = %c\n", *(cptr + 1));

    return 0;
}

Output:

iptr      = 0x7ffc...
iptr + 1  = 0x7ffc...

cptr      = 0x7ffc...
cptr + 1  = 0x7ffc...

*iptr     = 10
*(iptr+1) = 20

*cptr     = A
*(cptr+1) = B

iptr is an integer pointer, so adding 1 moves the address by sizeof(int) bytes.

cptr is a character pointer, so adding 1 moves the address by 1 byte.

Pointer arithmetic always depends on the datatype associated with the pointer.

Arrays are stored continuously in memory, and pointer arithmetic is commonly used to traverse array elements.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *