0

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

If I have a pointer and I know the indexes of both the chars, how would I swap the chars(I didn't actually allocate an array)

i.e.

char *str = "hello" and I know and I wanted to swap the 'h' and 'o' which is index 0 and 4, and then return the pointer as well.

I'm used to doing the convention of

temp = array[i];
array[i] = array[j];
array[j] = temp;
Community
  • 1
  • 1
Brandon Ling
  • 3,841
  • 6
  • 34
  • 49

4 Answers4

3

Well, you can't with pointer to a string literal. Literals are immutable. Stick with the way you've always done it.

Lews Therin
  • 10,907
  • 4
  • 48
  • 72
1
temp = array[i];
array[i] = array[j];
array[j] = temp;
Nico
  • 3,826
  • 1
  • 21
  • 31
1

The following declaration:

char *str = "hello";

Should be, to warn you about unsafe behaviors:

const char *str = "hello";

Because attempt to modify a string litteral is an undefined behavior according to C standard, you should rather use an array.

char str[] = "hello";

Then, swap the array's elements is easy and safe:

char tmp = str[0];
str[0] = str[4];
str[4] = tmp;
md5
  • 23,373
  • 3
  • 44
  • 93
0

Some operating systems / compilers allow you to do modify string literals, mainly AIX 5.1.

If modify the string literal in your code, it makes it a pain to have your code cross platform as you have to rewrite your code to compile for Linux.

Doug
  • 3,472
  • 3
  • 21
  • 18