-3

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Phil O'kelly
  • 161
  • 1
  • 3
  • 14
  • You hardly want to "assign an element from a pointer the same value as another element from the same pointer", but from the objects they **point to**! Also you want to read [ask] and provide a [mcve]. – too honest for this site Oct 04 '16 at 12:04
  • This code attempts to modify a string literal (which is undefined behavior) on a string that nothing outside of the function has access to; what exactly are you trying to achieve? – Scott Hunter Oct 04 '16 at 12:05
  • @Olaf There is nothing wrong with the question as far as SO policies go. The code posted contains a MCVE. The only problem here is the lack of research before asking a FAQ. – Lundin Oct 04 '16 at 12:59
  • @Lundin: I miss what OP expects and what he gets. "Doesn't work" is not a specific statement. – too honest for this site Oct 04 '16 at 14:32

3 Answers3

4

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

When you write char *p = "123", p points to the first element of 4 characters of read-only memory. Really you should write const char* p = "123" to induce a compile-time failure on the statement p[0] = p[2];.

If you want to modify the string then use automatic storage duration; i.e. write

char[] p = "123";

p is then a char[4] type, with a nul-terminator for the final element.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • The standard does not require the memory to be read-only. It just says it must not be changed by the programmer. But then it allows implementations to provide modifyable memory. – too honest for this site Oct 04 '16 at 12:07
0

char *p = "123";

When you define a pointer like this it will save the data in read-only memory segment, that is the reason you are not able to modify the data