Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap function for a char*

Tags:

c

swap

I have the simple function below which swap two characters of an array of characters (s). However, I am getting a "Unhandled exception at 0x01151cd7 in Bla.exe: 0xC0000005: Access violation writing location 0x011557a4." error. The two indexes (left and right) are within the limit of 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++. Thanks!

like image 600
Martin Avatar asked Dec 05 '25 21:12

Martin


2 Answers

You can't modify a string literal. instead try this:

char s[] = "ABC"
swap(s, 0, 1);
printf("%s\n", s);
like image 120
Evan Teran Avatar answered Dec 07 '25 17:12

Evan Teran


"ABC" is in the RODATA section, so you can't change it, please see the assembly:

        .section        .rodata
.LC0:
        .string "ABC"
like image 32
wenlujon Avatar answered Dec 07 '25 16:12

wenlujon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!