Re: Is C-style string unchangable?
"Xiaoshen Li" <xli6@gmu.edu> wrote in message
news:dp3tt5$gmo$1@osf1.gmu.edu...[color=blue]
> Dear All,
>
> I hear a lot that cstring cannot be changed.[/color]
If by 'cstring' you mean the 'C-style string', i.e. a zero-terminated
array of characters, then you heard wrong. For various reasons, *some*
C-style strings are not modifiable in a defined way. To state this about
*any* such string is simply wrong.
What cannot be modified is an array whose elements are const:
const char arr[] = "Attempts to modify this string"
" should result in compiler diagnostic";
or a string literal:
char *p = "I am a literal";
p[0] = 'i'; // undefined behavior.
[color=blue]
> But my code:
>
> /************************************************** ***********
> * Testing cstring(a pointer)[/color]
There are no pointers declared or defined in your code.
[color=blue]
> * ************************************************** ********/
> #include <iostream>
> using namespace std;
>
> int main()
> {
> char shortsTring[] = "abc";[/color]
This is an array of four type 'char' objects. It is not a pointer.
[color=blue]
> shortsTring[2] = 'X';[/color]
This replaces the object at shortsTring[2] with the character value 'X'
The string now contains: "abX"
[color=blue]
>
> cout << shortsTring << endl; //print out abX !!![/color]
This is expected and normal behavior. You created a 'normal'
non-const (i.e. modifiable) array of characters, changed the
value of one of those characters, then inserted all the characters
into the output stream designated by 'cout'.
Which C++ book(s) are you reading?
[color=blue]
>
> return 0;
> }[/color]
-[color=blue]
>
> So why many people are saying cstring cannot be changed?[/color]
Two possibilites:
1. They're simply wrong.
2. You've misunderstood.
Depending upon context, some objects are modifiable, others are not.
The types of these objects (such as char, or arrays thereof), makes
no difference.
[color=blue]
>Could you help me? Thank you very much.[/color]
The best help I can offer is to advise you to abandon the use
of character arrays for representing strings in C++, and use
the 'std::string' type (declared by <string>), which was created
specifically for the purpose.
-Mike |