In article < .com>,
<> wrote:
>On Apr 5, 1:09 pm, "Erik Wikstr=F6m" <eri...@student.chalmers.se> wrote:
>> On 5 Apr, 07:35, "liujiaping" <ljiap...@gmail.com> wrote:
>> > I'm confused about the program below:
>>
>> > int
>> > main(int argc, char* argv[])
>> > {
>> > char str1[] =3D "abc";
>> > char str2[] =3D "abc";
>> > const char str3[] =3D "abc";
>> > const char str4[] =3D "abc";
>> > const char* str5 =3D "abc";
>> > const char* str6 =3D "abc";
>> > //str6[0] =3D 'd'; // of coz error
>> > char* str7 =3D "abc";
>> > //str7[0] =3D 'd'; // error too
>> > cout << boolalpha << (str1 =3D=3D str2) << endl; // false
>> > cout << boolalpha << (str3 =3D=3D str4) << endl; // false
>> > cout << boolalpha << (str5 =3D=3D str6) << endl; // true
>> > cout << boolalpha << (str6 =3D=3D str7) << endl; // true
>> > return 0;
>> > }
>
>I ever have found this problem. In the source above,
>if you want to get or set the value of str7, you can add
>"*" before str7.
But only if it points to a modifiable entity.
Of course, if it is modifiable, it need not only be the first
char that can be modified.
>So, you can write " *str7[0] =3D 'd' ".
No, that's a double dereference (& and []).
So you meant either *str7 = 'd'; or str7[0] = 'd';
However, that runs into another problem: pointing to
a string literal, as the str7 initializer establishes,
means that you should only read from and not write through
that pointer. There reason why is because C or C++ may
put the string in a read only area (and string literals are
literally const in C++ BTW) and also might do something like
merge similar string literals.
Note that this is not the case with say str1[] because post
initialization, str1 is 'a' 'b' 'c' '\0' which is different
than str7 which points to an unnamed array. If one did
str7 = str1; there would not be the string literal problem
mentioned above.
Anyway, so str1 and str2 are distince addresses, hence
the first output will be false, ditto for str3 vs str4.
This compares addresses not content at the addresses.
However, str5 vs str6, and str6 vs str7, may be either
true or false, we don't know which until we run the program
with a specific compiler in a specific mode, and even at that,
it could theoratically be ramdom results, because "abc" here
and "abc" there may or may notbe the same unnamed array.
>why we must add "*", same with Erik say that str7 is pointer.
???
--
Greg Comeau / 4.3.9 with C++0xisms now in beta!
Comeau C/C++ ONLINE ==>
http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?