-2

I have to answer if the following code compiles and which are the results:

char *s1 = "A String";
char *s2 = "Other String";
*s1 = *s2;

I didnt really find what happens in the background when you do declarations like that. Is s1 pointing to memory looking like this?:

|A| |S|t|r|i|n|g|\0|

In my understanding *s1 = *s2 is the same like s1[0] = s2[0], right? So why do I get a memory error? Shouldnt it be?:

|O| |S|t|r|i|n|g|\0|
homior
  • 161
  • 1
  • 12

1 Answers1

1

Literals strings in C are really read only arrays of characters, and can (and should) not be modified.

Attempting to modify the contents of a string literal leads to undefined behavior.

Always make it a habit to use const char * when having pointers to string literals.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621