1

C++ - This program gives a run-time break error at line 2.

char * ptr = "hello";
(*ptr)++;            // should increment 'h' to 'i'
cout<<ptr<<endl;     // should display 'iello' 

Unhandled exception at 0x004114b0 in test.exe: 0xC0000005: Access violation writing location 0x00417830.

Any idea why it is giving this error? Whereas if I run the following code, it works absolutely fine.

char arr[] = "hello";
char * ptr = arr;
(*ptr)++;           // increments 'h' to 'i'
cout<<ptr<<endl;    // displays 'iello'

2 Answers 2

3

Because you are trying to change read-only memory. There is a C FAQ which is adequate, even if this is a C++ question.

Basically when saying char *ptr = "hello" the compiler is free to place "hello" in read-only memory so it's not safe to try to write to it.

Another C FAQ might be useful:

What is the difference between these initializations?

char a[] = "string literal";
char *p  = "string literal";
Sign up to request clarification or add additional context in comments.

4 Comments

They way I am changing it in the second portion of code, isn't that also read-only memory?
@Saad Read the link I provided, it explains that too :-)
thanks! much appreciated. But why does compiler treats *ptr++ and ptr++ the same way? Its only when I place brackets around (*ptr)++ that it behaves differently.
@Saad Look for "operator precedence" in your book.
-1

When you declare char * ptr = "hello"; it means ptr is pointing to a constant string

when you say ptr++ , You are trying to change the base address which is not correct

3 Comments

ptr++ or *ptr++ doesnt give any error. But when I place quotes, (*ptr)++ then it gives an error. I am not trying to change the base address, rather modifying the contents located on that address.
While it's true that ptr is pointing to a constant string, ptr++ would be perfectly valid (moving the pointer on). However, the question involves (*ptr)++ - incrementing the value currently pointed to.
as @cnicutar pointed out char * ptr = "hello"; instructs the compiler that ptr is pointing to a constant string . whereas in case of char arr[] = "hello"; char * ptr = arr; ptr is a non const pointer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.