From: Maurice L. <mj...@br...> - 2008-08-14 18:02:29
|
On Thursday, August 14, 2008 at 12:56:45 (-0500) Maurice LeBrun writes: > On Thursday, August 14, 2008 at 10:18:32 (-0700) Alan W. Irwin writes: > > On 2008-08-14 09:58-0500 Maurice LeBrun wrote: > > > > > For C & C++, a const pointer means the memory it points to cannot be altered. > > > The pointer can. So for example > > > > > > const char *foo = "bar"; > > > > > > (or later reassignment) is perfectly legit. > > > > After years of dabbling at C, this pointer stuff still makes my head spin so > > could you expand a bit more, Maurice? What actually happens with the above > > statement? After the declaration of foo as a pointer to a const char is foo > > initialized as a pointer to the first character in the const "bar" string? > > Correct. > > > Or would a better way to look at it be that all character strings like "bar" > > can be interpreted as pointers so the above is simply a pointer assignment? > > This too is correct. All string literals in a program are stored in the > executable, as a `strings <program>` will demonstrate. The proper way to > refer to these is via a const char* since they are considered fixed. > > If you want a char* string that's modifiable, you need to define a character > buffer and copy a string into it. Whenever unsure, just construct a simple > test and try it (I keep several handy for that purpose). For example, what > if you assign a literal to a char* and then try to modify it? > > char *foo = "0"; > foo[0] = "1"; > > then gcc complains: > tst.cc: In function ‘int main(int, char**)’: > tst.cc:15: error: invalid conversion from ‘const char*’ to ‘char’ Whoa, tripped up in my own example. This is a syntax error because "1" is a const char *, and foo[0] is a char. This is what I meant to write: char *foo = "0123"; foo[0] = '0'; Now gcc doesn't complain, since you're assigning char to char. But what happens when I run the program? $ ./tst Segmentation fault (core dumped) since I was trying to write into unmodifiable memory. > because apparently it's smart enough to know that even tho foo is defined as > char*, it's actually pointing to a const char*. I'm no language lawyer, but > it would seem that this syntax is supported for legacy reasons. Forget this part, I was mistaken. -- Maurice LeBrun |