Swap function for char *

I have a simple function below which swap two characters of an array of characters (s). However, I get "Unhandled Exception at 0x01151cd7 in Bla.exe: 0xC0000005: Location of Access Violation 0x011557a4." error. Two indexes (left and right) are within the array. What am I doing wrong?

void swap(char* s, int left, int right) {
    char tmp = s[left];
    s[left] = s[right];
    s[right] = tmp;
}

swap("ABC", 0, 1);

I am using VS2010 with unmanaged C / C ++. Thank!

+3
source share
2 answers

You cannot change a string literal. try the following instead:

char s[] = "ABC"
swap(s, 0, 1);
printf("%s\n", s);
+8
source

"ABC" is located in the RODATA section, so you cannot change it, see the assembly:

        .section        .rodata
.LC0:
        .string "ABC"
+1
source

Source: https://habr.com/ru/post/1742218/


All Articles