Sunday, January 9, 2011

Notes

K&R had something to say on my Question #1.

My Question: I thought that string literals had to be constant and couldn't be modified. This doesn't appear to be the case, but why?

K&R page 104 section 5.5:

char *pmessage = "now is the time";

...pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents...


So that somewhat answers the question - nobody is going to stop you from doing it, but it's a bad idea. I've noticed that the phrase "undefined" in C literature usually means this.

This section (5.5) drives home that the following:

char amessage[] = "now is the time";

and

char *pmessage = "now is the time";

look the same but are not the same. amessage is an array just big enough to hold the sequence of characters (and terminating zero) that initializes it. pmessage is a pointer initialized to point to a string constant. I get confused easily because you can pass amessage somewhere (without the array index) and it means &amessage[0] which makes just amessage look like the pointer to a string, but it's just a pointer to the first element. I think I've written before about how I can't treat them the same. It's hard to internalize. It's even hard to know when something is a no-no when the compiler doesn't warn you!

No comments:

Post a Comment