user3858
user3858

Reputation: 129

c++ beginner---string modification using pointer

I just started learning the relationship between pointers and arrays. What I read from this thread(What is the difference between char a[] = ?string?; and char *p = ?string?;?) is the string pointed by the pointer can not be changed. But in the following piece of code, I can change the string pointed by pa from abc to abd without any problem.

int main()
{
    char *pa;
    pa="abc";
    cout<<pa<<endl<<endl;
    pa="abd";
    cout<<pa<<endl<<endl;
    return 0;

}

However, it does not work in this piece of code. Can someone explain the difference to me? Thank you very much!!

int main()
{
    char *pc;
    pc="abc";
    cout<<pc<<endl<<endl;
    *(pc+2)='d';
    cout<<pc<<endl<<endl;
    return 0;
}

Upvotes: 0

Views: 147

Answers (3)

herohuyongtao
herohuyongtao

Reputation: 50657

Normally, string literals are stored in read-only memory when the program is running. This is to prevent you from accidentally changing a string constant. That's what happened in the second example, i.e. you will get a segmentation fault error.

This didn't happen in your first example because you are not changing the string itself. Instead, you just changed char *pa from pointing to one string to another.

You may need to check out: Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?


P.S. I recommend you to use string if you do need to change some part of it.

string pc = "abc";
pc[2] = 'd'; 

Here, read-only "abc" is copied into non-const pc to enable you to change its content.

Upvotes: 1

arjun8012
arjun8012

Reputation: 29

@user3858 I don't know whether you are aware of static,automatic and dynamic memory allocations or not but let me tell you that 'pa' is your automatic (pointer) variable initially pointing to a static memory region "abc" and which you later shifted it to point to some other memory region filled with "abd"."abc" and "abd" ,both are separate regions.And in your second program you are actually making a change in the "abc" region to make it "abd" and for which you are encountering an error.

Upvotes: 1

51k
51k

Reputation: 1443

In the first case you are not changing the string, actually, what is happening is first you were pointing to "abc" (pa="abc";) then you are making the pointer to point to "abd" (pa="abd";), the previous string i.e."abc" remains unchanged in the memory.

And in the second case your pc pointer is pointing to the same string, and the statement *(pc+2) = d tries to modify the value pointed by pc, which cannot be done.

Upvotes: 3

Related Questions