I had an embarrassing moment on SO where a user asked if it was safe to pass a String literal to a function. I answered that passing either a `char*` or `char[]` would create a `char*` on the stack once the function was called. Because of my misunderstanding I said that changing the address of the char* is legal even if its declared `const`. But what I didn't know was changing the char array pointed it pointed to was also legal.
So I tried myself and lo and behold it works even if the parameter in the function `func()` is `const`! But its illegal to change an element within the array? It just seems inconsistent to me.
Here is the code I wrote:
Code:
#include <stdio.h>
void func(const char *x, int* y) {
printf("func output:\n");
printf("%p\n", x);
printf("%s\n", x);
x = "New string"; //how is this legal?
x = x + 1000; //chage address pointed to by the char*
printf("%s\n\n", x);
printf("%p\n", y);
printf("%d\n", *y);
y = y + 10;
printf("%p\n", y);
printf("%d\n", *y);
}
int main(void) {
const char* ptr = "String";
int x = 25;
int * int_ptr = &x;
func(ptr, int_ptr);
puts("In main() \n");
printf("%s\n", ptr);
ptr = "New string";
printf("%s\n", ptr); //able to change the string literal. Why?
return 0;
}