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;
}
                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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With