C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 4)
4.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    char str[20] = "Hello";
    char *const p=str;
    *p='M';
    printf("%s\n", str);
    return 0;
}
Mello
Hello
HMello
MHello
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
69 comments Page 4 of 7.

Prasad said:   1 decade ago
Guys a pointer variable whose address never changed is called pointer constant. So here we can't change the address but we can change the value at that address
int x=10;
int *const p=&x;
int y=50;
p=&y;// wrong

And constant pointer means whose value can never be changed
const int *p;
int x=10;
p=&x;
*p=20;// can't modify the existing value..

M.Bhagya said:   1 decade ago
Here p contains the base address and that value H is replaced by M.

Tulshiram said:   1 decade ago
As given example
char*const t="Hello";
in this statement we have see pointer is constant but String t is not that why next statement
*t='M';
it is a String pointer which point base address is nothing but 'H'
so it will replace with it and give output: "Mello"

M@c said:   1 decade ago
If I change , Then what will be the o/p ?

char str[20] = "Hello";
char *const p=str;
// 1)
*p='Ma';
// 2)
*p='Mah';

Tell me for both the cases.

Jagadish said:   1 decade ago
As p is a constant pointer how we can change the value when it is assigned?

Dragon said:   1 decade ago
If we put *p=bye then answer is eello.

Can any one explain how?

Sushama said:   1 decade ago
Here p is the base address of str, we only modify the base address to m &then str becomes "mello".

Seema said:   1 decade ago
Here p is constant pointer and not pointer to constant.

So we can change the value of str using p but we can't assign new address to p.

Karthi said:   1 decade ago
char const*p is represent a constant pointer p not the value it holds so you can change the value but in const char*p is vice versa.

Himanshu said:   1 decade ago
We are not modifying the string of str ,
Then how it can change.

char str[20] = "Hello";
char *const p=str;
*p='M';
printf("%s\n", str);

Here we have not change the str[20] = "Hello".

I didn't get,
Please Tell me the reason.


Post your comments here:

Your comments will be displayed after verification.