0

there are two types for initializing string

constant pointer char p[]="quest"

pointer to constant char *p="quest"

i have read in a book that we cannot change value that pointer is pointing to,in pointer to constant so *p='M' should be invalid. but following code compiles.why?

#include <stdio.h>

int main(void) {
#include<stdio.h>
int main()
{
    char *p="quest";
    *p='M';
    getchar();
    return 0;
}

link to program-http://ideone.com/YsJ1t9

codeluv
  • 305
  • 1
  • 15
  • There are numerous dups of this. You can search and read. To summarize: modifying string literal is is *undefined* in C. The fact it *compiles* doesn't mean it's a valid code. – P.P Jul 02 '15 at 17:21
  • Just try to print the string @codeluv and you will see how it fails. – ckruczek Jul 02 '15 at 17:21
  • Here's another: http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha – P.P Jul 02 '15 at 17:24
  • @BlueMoon thanks ... the previous post you quoted had a gr8 explanation – codeluv Jul 02 '15 at 17:32

0 Answers0