I’m thrilled. Why does this works fine:
char ptr[] = "hello world!";
ptr[0] = 'H';
printf("%s\n", ptr); // prints "Hello world!"
and this:
char * ptr = "hello world!";
ptr[0] = 'H';
printf("%s\n", ptr);
raises a Segmentation Fault?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because the ptr[] is modifiable by the standard but the char * is not. The char * uses a const string which can be used many times over in the program the array actually creates a new array and copies your string to it.
By the way this should give a compile error – you must use
Adding some more – basically the compiler is allowed to look for every string in quotes and place it in a read only string table. Because a 1000 place in your program could use and define the string “this”. The compiler can get smart and convert those 1000 “this” to just 1 because they are all the same – because of this it becomes read only – So now one location cannot modify the fixed string after compile time – because it will break you expected output from your program.