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 3 of 7.

Nithya said:   1 decade ago
How to replace the second letter of the word "hello" by m ?

Murthy said:   1 decade ago
#include<stdio.h>

int main()
{
char str[20] = "Hello";//here given char str is hello
char *const p=str; //char * const p="hello" i.e str
char const *p="hello" so
*p='M'; //*p=M so it is changed H to M
printf("%s\n", str); // its prints Mello
return 0;
}

NOTE:

const char *p="hello";
char const *p="hello";

char * const p="hello";
const char * const u="hello";

Anonymous said:   1 decade ago
Here, str is copied to p and the value of p was changed. So, data in p is of str but not str=p. then if value in p is changed., How the value in str would change?

Sushmitha said:   1 decade ago
@Red.

The string str is assigned with str[0]='H', str[1]='e' and so on.
The other way of initialising that string would be
char str[]={'h','e','l','l','o','\0'};

NOTE: The name of the array itself holds the base address of the string.
So when p=str,the base address of the string str[0] is assigned to p.

*p='M' implies that the value at p which is str[0]is changed to 'M', which was previously 'H'.

Hope you got it.
(1)

Red said:   1 decade ago
Why is 'M' given? shouldn't it be "M"?

Chethan said:   1 decade ago
@Himanshu.

The string has got changed because we are accessing it through pointer that is we are directly writing to the address of string.

Swetha sathish k said:   1 decade ago
char *const p means p pointer is a constant. but the array is not.

Swetha sathish k said:   1 decade ago
Here pointer is constant, but not the string.

Pankaj pandey said:   1 decade ago
But how it is possible because string constraint never change, if we want to change the base address that is possible.

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.