int main ()
{
char *arr= "abt"; // This could be OK on some compilers ... and give an access violation on others
arr++;
*arr='e'; // This is where I guess the problem is occurring.
cout<<arr[0];
system("pause");
}
In contrast:
int main ()
{
char arr[80]= "abt"; // This will work
char *p = arr;
p++; // Increments to 2nd element of "arr"
*(++p)='c'; // now spells "abc"
cout << "arr=" << arr << ",p=" << p << "\n"; // OUTPUT: arr=abc,p=c
return 0;
}
This link and diagram explains "why":
http://www.geeksforgeeks.org/archives/14268
Memory Layout of C Programs
A typical memory representation of C program consists of following
sections.
- Text segment
- Initialized data segment
- Uninitialized data segment
- Stack
- Heap
And a C statement like const char* string = "hello world" makes the
string literal "hello world" to be stored in initialized read-only
area and the character pointer variable string in initialized
read-write area.