0

I am trying to assign the pointer y to pointer x, *x = *y but it crashes if testChar is pointer.

char *testChar = "abc";
char *x = testChar;
char *y = testChar + 1;
char temp;
temp = *x;
*x = *y;
*y = temp;

If I change the code as char testChar[] instead of *testchar its working good. Could any one explain me the differences?

Sujananth
  • 635
  • 1
  • 10
  • 24
  • `*x = *y;`? o.O – WedaPashi Apr 19 '18 at 10:52
  • 1
    Also, this is extensively discussed in SO. Your `testChar` should be `const` because it's pointing to a string literal which is a read only object. In [tag:c] however, you can use `const` to prevent accidentally modifying something that you don't want to modify, but it's ultimately your responsability to prevent it. – Iharob Al Asimi Apr 19 '18 at 10:55
  • char testChar[] = "abc"; char *x = testChar; char *y = testChar + 1; char temp; temp = *x; *x = *y; *y = temp; This program help to swap. I found it in geeks of geeks. I have not played with character array in c. Unable to understand it – Sujananth Apr 19 '18 at 10:56
  • @Sujananth you found solution yourself. What do you need here? – trungduc Apr 19 '18 at 10:57
  • 1
    Unable to understand why it crashes – Sujananth Apr 19 '18 at 10:58

1 Answers1

3

The string "abc" is stored in a read-only memory (the binary of your program). Thus, you are trying to modify read-only data, which is impossible.

Instead, you can do this:

char *testChar = strdup("abc"); // allocate new (writable) memory and copy this const string there.
char *x = testChar;
char *y = testChar + 1;
char temp;
temp = *x;
*x = *y;
*y = temp;

Note that testChar points to memory that you're responsible to free when you don't need it anymore (same as a malloc).

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
  • 1
    I assume the memory returned by `strdup` should be manually freed? I'd add it to the code. – FreeNickname Apr 19 '18 at 11:06
  • 1
    @FreeNickname true. I've updated my answer. – Maxime Chéramy Apr 19 '18 at 11:08
  • Also, don't assume that `strdup()` returned a valid pointer. Check for `NULL` in real code. – Iharob Al Asimi Apr 19 '18 at 11:15
  • Also don't assume strdup exists because it is not standard. There is no obvious reason to use heap allocation here in the first place. Also don't answer this incredibly common FAQ, but close as duplicate. – Lundin Apr 19 '18 at 11:20
  • @MaximeChéramy , In above code *x is getting value "abc" and *y is getting value "bc" after assigning *x = *y, the value of x is changed to bbc ? Could you please explain how its working. – Sujananth Apr 19 '18 at 16:44
  • 1
    You must print using printf("%c") and not %s. %s is stopping at the next \0 character. *x and *y store only one character. y points to the second character and x points to the first character. This hasn't changed. – Maxime Chéramy Apr 19 '18 at 19:52