Option some compiller for 1 problem in C/C++

I have a problem like that :

1
2
3
4
5
6
7
8
int main()
{
        char *s ="hello world";
        s[0]='H';
        cout << s << endl;;
        return 0;
}


Because "hello world" is a const data.So,we can't modify data on this memory (read-only data).But if i use :

char s[] ="hello world";

It's OK because "hello world" is in stack data.So,we can read and write.

But,if i compile on VC++ 2005 with option:

cl.exe /DEBUG /Zi /W4 /EHsc test.cpp

It works well !!

I try on VC++ 2008 with above option.It 's not sucessful.

What can I do like this on VC++ 2008 and other compiler such as Gcc ??

acturally, In C++, the string literal like "hello,world" is really a constant, and in most cases, s will convert to a pointer to the first char 'h',but the standard doesn't require the converted result to be const.The standard also says, modify the string literal is undefined, that means anything could happen, including nothing wrong.

C++11 2.14.5.12
Last edited on
char *s where is the s = new char[n]; and respective delete [] s ;in your code

you cant do some thing like char *s ="hello world";

either do that like char s[] ="hello world"; or use new and delete operators
Please help me !!!
Please help me !!!


Use a proper C++ string.

1
2
3
4
5
6
7
int main()
{
        string s("hello world");
        s[0]='H';
        cout << s << endl;;
        return 0;
}
Last edited on
No,Moschops !!

I need to know what compiler can compile and run it succesfully , not how to change value of pointer s on code !!
Last edited on
I need to know what compiler can compile and run it succesfully


VC++ 2005 with option: cl.exe /DEBUG /Zi /W4 /EHsc test.cpp will compile and run it successfully.
closed account (1yR4jE8b)
You shouldn't be trying to "get this to run successfully". It's not standard C++, or even C, for that matter. It's not supposed to work. Stop trying to do things that are dangerous and non-standard, people that work with you in the future are going to hate you.
Last edited on
Topic archived. No new replies allowed.