开发者

Swap function for a char*

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!


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

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


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

        .section        .rodata
.LC0:
        .string "ABC"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜