Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I change the value of a const char* variable?

Why does the following code in C work?

const char* str = NULL; str = "test"; str = "test2"; 

Since str is a pointer to a constant character, why are we allowed to assign it different string literals? Further, how can we protect str from being modified? It seems like this could be a problem if, for example, we later assigned str to a longer string which ended up writing over another portion of memory.

I should add that in my test, I printed out the memory address of str before and after each of my assignments and it never changed. So, although str is a pointer to a const char, the memory is actually being modified. I wondered if perhaps this is a legacy issue with C?

like image 445
Chris Avatar asked Jan 13 '09 19:01

Chris


People also ask

Can const char * Be changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

Can we change the value of const variable?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).

What is the difference between const char * and char * const?

The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).

Can a char * be passed as const * argument?

In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...


1 Answers

You are changing the pointer, which is not const (the thing it's pointing to is const).

If you want the pointer itself to be const, the declaration would look like:

char * const str = "something"; 

or

char const * const str = "something";  // a const pointer to const char const char * const str = "something";  //    same thing 

Const pointers to non-const data are usually a less useful construct than pointer-to-const.

like image 127
Michael Burr Avatar answered Oct 20 '22 18:10

Michael Burr