-2

Why do I get exception in the code?

char* first = "first";
char* second = "second";
*first = *second;

Shouldn't it just assign values? Error message says: access violation

1 Answers1

0

No because they are string literals and are read only

char *first = "first";
char *second = "second";

you can try with arrays instead.

char first[] = "first";
char second[] = "second";

to prevent this kind of error you can do this

const char *first = "first";
const char *second = "second";

when declaring string literals, it will not prevent the problem completely because you still can cast away the const but you should do so conciously.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • 1
    Technically, string literals are not unmodifiable. It's just that writing to them constitutes *undefined behaviour.* – fuz Jan 18 '15 at 13:19