Hi experts
Why i get run-time error with this:
char *temp ="string";
temp[2] = '\0'; // < get errror here?
Memory address is not being touched but only a value which resides on the memory is being altered, there should not be any problem doing this?
A string literal like "string" is stored in non-writable memory (with most C compilers). So, the pointer temp is pointing to a memory location that you're not allowed to write to. When you try to write to it anyway, it causes a runtime error. There are a couple of ways you can get around this problem:
char temp[] = "string"; // works if temp is a global variable
char temp[7]; // remember to allocate an extra byte for the terminating null!
strcpy(temp, "string");
Either one of these approaches gives you a buffer in writable memory that is filled with the value "string".