4

I need to swap two characters by pointers but when I run this code,the program crashes.

int main(){
    char *s1 = "string1";
    swap(st,(st+1));

    /* BUT THIS CODE WORKS - Whats the problem?
     * char s1[] = "string1";
     * swap(s1,&s1[1]);
     */

    return 0;
}

void swap(char * const ptr1, char * const ptr2){

    char temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;

}
Arpit
  • 12,767
  • 3
  • 27
  • 40
g3d
  • 453
  • 2
  • 6
  • 14
  • Because, when you allocate memory for amount of characters, it's only readable, not executable or writable. When you try to write there, it gives you exception. – Nika Jan 27 '13 at 11:45

3 Answers3

5
char *s1 = "string1";

Because s1 points to a string literal and modifying invokes undefined behaviour in C. That's why this doesn't work.

Whereas in this char s1[] = "string1";

s1 is an array and hence it can be modified.

P.P
  • 117,907
  • 20
  • 175
  • 238
2

A string literal may not be modified. You try to modify "string1" in your code which is not allowed. Indeed, many compilers place string literals in a special section that may not be written into.

fuz
  • 88,405
  • 25
  • 200
  • 352
1

This line of code creates a string literal which cannot be changed. It is only readable.

char *s1 = "string1";

Any attempt to change it will give you an error.

While your commented example :

 char s1[] = "string1";

creates an actual array. This can be edited and used normally.

asheeshr
  • 4,088
  • 6
  • 31
  • 50