Using Constant Pointers in C Programming


In C, a pointer can be declared as "const" to indicate that the memory location it points to should not be modified.

  • This program demonstrates the use of a constant pointer to a character array. The first line declares a character array "a" of size 3, and initializes it with the characters 'a', 'b', 'c'. Then it declares a constant pointer "p" to the character array "a".
  • The program then uses the printf statement to print the value stored at the memory location pointed by the pointer "p" using the dereference operator (*p) which is 'a'
  • Then it modifies the value of the memory location pointed by the pointer by using the dereference operator and assigning a new value 'x' to it.
  • Then it tries to increment the pointer but it will give an error as pointer is declared as const, it cannot be changed.
  • Finally, the program again uses the printf statement to print the value stored at the memory location pointed by the pointer "p" after modification which is 'x'

Source Code

//Const
#include<stdio.h>
 
 
int main()
{
    //Case 3:
 
    char a[3]={'a','b','c'};
    char  * const p=a;
 
    printf("\n *p = %c",*p);
 
    *p='x';
    //p++; //Cannot change the value its const
    printf("\n *p = %c",*p);
 
    return 0;
}
 
 
 
/*
 
 
  //Case 1:
 
    char a[3]={'a','b','c'};
    const char *p=a;
 
    printf("\n *p = %c",*p);
 
    //*p='x';  // Cannot change the value its const
    p++;
    printf("\n *p = %c",*p);
 
 
*/
 
/*
//Case 2:
 
    char a[3]={'a','b','c'};
    char const *p=a;
 
    printf("\n *p = %c",*p);
 
    //*p='x';  // Cannot change the value its const
    p++;
    printf("\n *p = %c",*p);
 
*/
 
 
 
To download raw file Click Here

Output

 *p = a
 *p = x

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C