Up vote 3 down vote favorite share g+ share fb share tw.
What is the difference between this: char arr = " world! "; And this: char *arr = " world! "; Where do both strings' memory get allocated?
Why am I not able to change content of latter string? C string link|improve this question edited Sep 14 '11 at 4:39muntoo3,22331121 asked Sep 14 '11 at 4:33teacher57310 62% accept rate.
3 Strictly speaking, the latter should read const char *arr = "hello world! "; – Nemo Sep 14 '11 at 4:39 1 @Nemo: It should, but strictly speaking C doesn't require it. C string literals are not const, but attempting to modify one is undefined behavior – Keith Thompson Sep 14 '11 at 5:25 1 @teacher: This question has been asked many times on SO.
A quick search gave these links. (a) stackoverflow.com/questions/1704407/… (b) stackoverflow.com/questions/1880573/… – Bhaskar Upadhyayula Sep 14 '11 at 8:02.
The first one is writable memory allocated specifically for arr, which is an array of chars. You can modify it without invoking undefined behavior. This is completely legal: char arr = " world!
"; arr1 = 'i'; The second one is a pointer to a read-only string. Therefore, this is undefined behavior: char *parr = " world! "; parr1 = 'i'; // Cannot write to read-only memory!
In some compiler implementations: char *a = " world! "; char *b = " world! "; a1 = 'i'; // b1 == 'i'; This isn't guaranteed - I'm only including it to give you an 'intuitive' feel of why it's undefined behavior.
– teacher Sep 14 '11 at 4:36 No, the read-only string is stored in a read-only part of the memory of you're process. – Simon Sep 14 '11 at 4:37 1 @teacher - arr resides on stack but the value pointed by arr resides on read only location whose location is implementation dependent. – Mahesh Sep 14 '11 at 4:42 1 err..No one mentions Second is called a String Literal?
– Als Sep 14 '11 at 4:50 1 @Jesus: That's one of the infinitely many possible results of undefined behavior. I just tried this with gcc: char *s = "hello, world"; s0 = 'H'; and the program died with a segmentation fault. – Keith Thompson Sep 14 '11 at 5:30.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.