• Home
  • Pointer Basics – Why Types to Pointers? (Part 1)

Pointer Basics – Why Types to Pointers? (Part 1)

View Categories

Pointer Basics – Why Types to Pointers? (Part 1)

< 1 min read

This example shows why pointers have types associated with them. Even though a pointer stores an address (an integer value), the type determines how many bytes are read from that address during dereferencing.



⚙️
main.c

Copy to clipboard

#include <stdio.h>

int main()
{
    double d = 2.5;
    char ch = 'A';

    int *iptr;
    char *cptr;
    double *dptr;

    printf("Sizeof *iptr = %zu\n", sizeof(*iptr));
    printf("Sizeof *cptr = %zu\n", sizeof(*cptr));
    printf("Sizeof *dptr = %zu\n", sizeof(*dptr));

    cptr = &ch;
    dptr = &d;

    printf("*cptr = %c\n", *cptr);
    printf("*dptr = %f\n", *dptr);

    return 0;
}

Output:
Sizeof *iptr = 4
Sizeof *cptr = 1
Sizeof *dptr = 8
*cptr = A
*dptr = 2.500000

Pointers store addresses, but the associated type defines how the data at that address is interpreted.

sizeof(*iptr), sizeof(*cptr), and sizeof(*dptr) show the number of bytes that will be accessed when dereferencing each pointer type.

cptr points to a char, so dereferencing reads 1 byte.
dptr points to a double, so dereferencing reads 8 bytes (on most systems).

The pointer type tells the compiler how many bytes to read or write at the memory location it points to.

Without type information, the correct interpretation of data at that address would not be possible.

Powered by BetterDocs

Leave a Reply

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