Phil O'kelly Phil O'kelly - 8 months ago 35
C Question

Assigning an element of a pointer to another element from the same pointer

I'm trying to assign an element from a pointer the same value as another element from the same pointer.

int testFunc() {
char *p = "123";
p[0] = p[2];
return 0;

Curious as to why the above code doesn't work - and what is the best way to achieve what I'm trying to do?


You are facing the issue because you're trying to modify a string literal which invokes undefined behavior.

The problem is in

 p[0] = p[2];

while p points to a string literal.

Quoting C11, chapter §6.4.5, String literals

[...] If the program attempts to modify such an array, the behavior is undefined.

You need to have an array instead, t be able to modify the contents, something like

 char parr[] = "123";

and then

 parr[0] = parr[2];

will do.