0

In the following code, why is not possible to do this dereferencing: *arr = 'e'. Shouldn't the output be the character 'e'?

int main ()
{
    char *arr = "abt";
    arr++;
    * arr='e'; // This is where I guess the problem is occurring.
    cout << arr[0];

    system("pause");

}

I am getting the following error:

Unhandled exception at 0x00a91da1 in Arrays.exe: 0xC0000005: Access violation writing location 0x00a97839.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
John Nash
  • 67
  • 5
  • If "abt" is a constant string literal, then why does the following code modify the same constant literal: int main (void) { char arr[]= "abt"; arr[0]='e'; cout< – John Nash Jul 01 '12 at 23:14
  • possible duplicate of [Why is this C code causing a segmentation fault?](http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation-fault) – AnT stands with Russia Jul 01 '12 at 23:19

2 Answers2

3

"abt" is what is called a string literal constant, any attempts to modify it result in undefined behavior *arr='e';.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • 1
    Then why I am able to do the following:int main (void) { char arr[]= "abt"; arr[0]='e'; cout< – John Nash Jul 01 '12 at 23:13
  • @JohnNash, [it had been already asked and answered long before you posted...](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c) – Griwes Jul 01 '12 at 23:18
  • 1
    `char arr[] = "abt";` is an array of characters, `char *arr= "abt";` is a pointer to a string literal that resides in read-only memory. – Jesse Good Jul 01 '12 at 23:19
0
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.

  1. Text segment
  2. Initialized data segment
  3. Uninitialized data segment
  4. Stack
  5. 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.

paulsm4
  • 114,292
  • 17
  • 138
  • 190