Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C : Character swapping [duplicate]

Tags:

c

char

pointers

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;

}
like image 387
g3d Avatar asked Feb 17 '23 17:02

g3d


2 Answers

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.

like image 193
P.P Avatar answered Feb 27 '23 09:02

P.P


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.

like image 29
fuz Avatar answered Feb 27 '23 09:02

fuz