C Programming - Const - Discussion

Discussion Forum : Const - Point Out Errors (Q.No. 1)
1.
Point out the error in the program.
#include<stdio.h>
#define MAX 128

int main()
{
    char mybuf[] = "India";
    char yourbuf[] = "BIX";
    char *const ptr = mybuf;
    *ptr = 'a';
    ptr = yourbuf;
    return 0;
}
Error: unknown pointer conversion
Error: cannot convert ptr const value
No error
None of above
Answer: Option
Explanation:

Step 1: char mybuf[] = "India"; The variable mybuff is declared as an array of characters and initialized with string "India".

Step 2: char yourbuf[] = "BIX"; The variable yourbuf is declared as an array of characters and initialized with string "BIX".

Step 3: char *const ptr = mybuf; Here, ptr is a constant pointer, which points at a char.

The value at which ptr it points is not a constant; it will not be an error to modify the pointed character; There will be an error only to modify the pointer itself.

Step 4: *ptr = 'a'; The value of ptr is assigned to 'a'.

Step 5: ptr = yourbuf; Here, we are changing the pointer itself, this will result in the error "cannot modify a const object".

Discussion:
3 comments Page 1 of 1.

Parth parmar said:   5 years ago
Answer A is correct.

Constant pointer can't change pointing variable once assign it,

Here first time assign mybuf then it can't point to youtbuf.

=> C compiler give an error.

Dharani.s said:   8 years ago
I can't understand. Please explain in detail.

Sandy said:   1 decade ago
#include<stdio.h>
const char *fun();

int main()
{
int a,b;

/* Pointer to int*/
a = 10;
b = 20;
int *ptr = &a;
printf("Pointer to int: before change = %d,%d\n",ptr,*ptr);
*ptr = 15;
printf("Pointer to int: after change value = %d,%d\n",ptr,*ptr);
ptr = &b;
printf("Pointer to int: after change address = %d,%d\n\n",ptr,*ptr);


/* Constant Pointer to int*/
a = 10;
b = 20;
const int* ptr1 = &a;
printf("Constant Pointer to int: before change = %d,%d\n",ptr1,*ptr1);
//*ptr1 = 15; /*Error*/
printf("Constant Pointer to int: after change value = %d,%d\n",ptr1,*ptr1);
ptr1 = &b;
printf("Constant Pointer to int: after change address = %d,%d\n\n",ptr1,*ptr1);

/*Pointer to constant int*/
a = 10;
b = 20;
int* const ptr2 = &a;
printf("Pointer to constant int: before change = %d,%d\n",ptr2,*ptr2);
*ptr2 = 15;
printf("Pointer to constant int: after change value = %d,%d\n",ptr2,*ptr2);
//ptr2= &b; /*Error*/
printf("Pointer to constant int: after change address = %d,%d\n\n",ptr2,*ptr2);

/*Constant pointer to constant int*/
a = 10;
b = 20;
const int* const ptr3 = &a;
printf("Constant pointer to constant int: before change = %d,%d\n",ptr3,*ptr3);
//*ptr3 = 15;/*Error*/
printf("Constant pointer to constant int: after change value = %d,%d\n",ptr3,*ptr3);
//ptr3= &b; /*Error*/
printf("Constant pointer to constant int: after change address = %d,%d\n\n",ptr3,*ptr3);

}
(1)

Post your comments here:

Your comments will be displayed after verification.