C Programming - Const - Discussion
Discussion Forum : Const - Point Out Errors (Q.No. 7)
7.
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;
}
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 a constant; it will be an error to modify the pointed character; There will not be any error to modify the pointer itself.
Step 4: *ptr = 'a'; Here, we are changing the value of ptr, this will result in the error "cannot modify a const object".
Discussion:
3 comments Page 1 of 1.
Suhail said:
5 years ago
The address of the pointer cannot be changed but the value can be changed.
=> char *const ptr: This is a constant pointer to a non-constant character.
=> char *const ptr: This is a constant pointer to a non-constant character.
Ahmed Yasen said:
7 years ago
Here, char const *ptr : ptr is a pointer to constant char.
Anonymous said:
1 decade ago
Correction in Step 3 of the explanation that ptr is not constant pointer, it is pointer to a constant. Hence the error when we try to modify the constant value.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers