C: Character Exchange

I need to swap two characters with pointers, but when I run this code, the program will crash.

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; } 
+4
source share
3 answers
 char *s1 = "string1"; 

Because s1 points to a string literal and modification causes undefined behavior in C. That's why this does not work.

While in this char s1[] = "string1";

s1 is an array and therefore it can be modified.

+4
source

String literal cannot be changed. You are trying to change "string1" in your code, which is not allowed. Indeed, many compilers put string literals in a special section that cannot be written.

+2
source

This line of code creates a string literal that cannot be changed. It is read-only.

 char *s1 = "string1"; 

Any attempt to change it will result in an error.

So far your comment:

  char s1[] = "string1"; 

creates the actual array. This can be edited and used normally.

+1
source

All Articles