Why can't I do ++*ptr with char*

This is the code:

#include <stdio.h>
using namespace std;

int main(void)
{

char* c="XYZ";
int p[] = {1,3,4};

int* i=new int[3];
i[0] = 1;
i[1] = 5;
i[2] = 10;

printf("%c\n",++*i);
printf("%c\n",++*p);
printf("%c\n",++*c);
return 0;
}


The ++*ptr works with i and p but I always get "unhandled exception" error when I do this with c. Why?
You are not allowed to modify the memory you get from a string literal, so for that reason it is more correct to use const char*. Modern compilers often warn you if you don't.

 
const char* c = "XYZ";

This will give you a compilation error instead of a runtime error if you accidentally try to modify the string.
Last edited on
char* c = "XYZ" ; is an error (since C++11)
http://coliru.stacked-crooked.com/a/f1e2b41625edff5f
Are you trying to say that once I declare:
char* c="XYZ";

I cannot modify c?

I may have assigned a string literal, but since it is not declared to be constant, I should be able to change value but I can't. Why? :(

So if I want to change the value of the string literal, is the only way to copy it into another char* (that is perhaps dynamically allocated depending on situation) along with the changes?
It doesn't have to be declared const to be deemed const:
https://msdn.microsoft.com/en-us/library/69ze775t(v=vs.120).aspx
I cannot modify c?
You can actually modify c (the pointer) but not the memory it points to since it is most likely in a read only memory.
> Are you trying to say that once I declare:
> char* c="XYZ";
> I cannot modify c?

No. I am saying that you cannot declare char* c="XYZ"; in a C++ program.
It will be diagnosed as an error by a conforming C++ compiler.

1
2
3
4
5
6
int main()
{
    char* c = "XYZ" ;
    // clang++: error: ISO C++11 does not allow conversion from string literal to 'char *' 
    //     g++: error: ISO C++ forbids converting a string constant to 'char*'
}

http://coliru.stacked-crooked.com/a/7069eb94c1b84932

Microsoft:
Microsoft Specific
In Visual C++ you can use a string literal to initialize a pointer to non-const char or wchar_t.
This is allowed in C99 code, but is deprecated in C++98 and removed in C++11.
https://msdn.microsoft.com/en-us/library/69ze775t(v=vs.140).aspx


Topic archived. No new replies allowed.