✏️ Explanatory Question

What is const pointer in C?

👁 978 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Const pointer is a pointer that can’t change the address of the variable that is pointing to.
Once const pointer is made to point one variable, we can’t change this pointer to point to any other variable. This pointer is called const pointer.

What is a Const Pointer in C?

A const pointer is a pointer whose address cannot be changed after initialization. In other words, once a const pointer is made to point to a particular variable, it cannot be made to point to another variable. However, the value stored at the pointed location can still be modified (if the data itself is not declared as const).

Syntax

data_type * const pointer_name = &variable;

Example:

int num = 10;
int * const ptr = #

Here, ptr is a const pointer. It must always point to num and cannot be assigned the address of another variable.

Example of a Const Pointer

#include 

int main() {
    int num = 10;
    int * const ptr = #

    *ptr = 20;   // Allowed

    printf("Value of num = %d\n", num);

    return 0;
}

In this example, the value of num is changed through the pointer. This is allowed because the data is not constant.

What is Not Allowed?

#include 

int main() {
    int num1 = 10;
    int num2 = 20;

    int * const ptr = &num1;

    ptr = &num2;   // Error

    return 0;
}

The above statement generates a compilation error because a const pointer cannot be made to point to a different memory address after initialization.

Key Characteristics of a Const Pointer

  • The pointer address cannot be changed.
  • The pointer must be initialized at the time of declaration.
  • The value pointed to can be modified (if the data is not constant).
  • Declared using * const.

Const Pointer vs Pointer to Const

Feature Const Pointer Pointer to Const
Declaration int * const ptr const int *ptr
Can Change Address? No Yes
Can Modify Value? Yes No

Memory Representation


num = 10

+------+        +------+
| num  | <----  | ptr  |
+------+        +------+

ptr always points to num
  

Key Point

A const pointer is a pointer whose address cannot be changed after it is initialized. It always points to the same memory location, although the value stored at that location can be modified unless the data itself is declared as const.