Skip to main content

Why datatype in pointer declaration

Short answer

While all pointers store addresses, the data type is required for correct dereferencing (determines how many bytes to read and how to interpret them), for pointer arithmetic that scales by sizeof the pointed type, and for compiler type checking to catch mismatched assignments.

A pointer variable is used to store address of some other variables, however, we need to specify datatype while declaring a pointer variable. Why?

All pointers store an address, which has the same size whatever the type. But the data type is still needed for the following reasons:

  1. Dereferencing: when *p is used, the compiler must know how many bytes to read from that address and how to interpret them. A char * reads 1 byte, an int * reads 4 bytes, a double * reads 8 bytes.
  2. Pointer arithmetic: p + 1 moves by sizeof the pointed type, not by 1 byte. For int *p, p + 1 is 4 bytes ahead, so it reaches the next integer in an array.
  3. Type checking: the compiler can warn when an address of the wrong type is assigned, e.g. int *p = &floatVar;.

Example: if the same 4 bytes are read through char * they give one character, but through int * they give a whole integer.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →