• Home
  • Pointer Basics – Arrays vs Pointers (Part 1)

Pointer Basics – Arrays vs Pointers (Part 1)

View Categories

Pointer Basics – Arrays vs Pointers (Part 1)

< 1 min read

This example demonstrates an important difference between arrays and pointers. A pointer variable can be modified to point to different locations, but an array name always points to the beginning of the array.



⚙️
main.c

Copy to clipboard

#include <stdio.h>

int main()
{
    int a[5] = {10, 20, 30, 40, 50};
    int *ptr;
    int i;

    ptr = a;

    for (i = 0; i < 5; i++)
    {
        printf("%d ", *ptr++);
    }

    printf("\n");

    /*
     * Not allowed
     * a++;
     */

    return 0;
}

Output:

10 20 30 40 50

ptr is a pointer variable, so its value can be changed.
Every time ptr++ runs, the pointer moves to the next integer element in the array.

The array name a also points to the first element of the array, which is why:

ptr = a;

works correctly.

But unlike ptr, the array name itself cannot be modified.

This is valid:

ptr++;

This is invalid:

a++;

because the array name always represents the fixed starting address of the array.

Powered by BetterDocs

Leave a Reply

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