Can we assign one co开发者_开发百科nst char * to another and modify the value?
const char * c1;
const char * c2 = c1;
Is the above assignment valid?
const char*
means that the contents of the string are constant. You can have different pointers referring to the same constant memory. In other words, the pointers are different variables with the same value. Remember that the value of a pointer is the address of the memory to which it refers.
So, yes, the assignment above is perfectly valid.
I wonder if this question is related to your previous question. You say here:
Can we assign one const char * to another and modify the value?
If by "modify the value" you mean modify the contents of the string (that's what you wanted to do in the previous question), then no you cannot. In the example you give here, you have two pointers referring to the same constant block of memory. If one of the pointers cannot modify that memory, then neither can the other.
const char*
means that the string pointed to is constant.
char const*
means that the pointer itself is constant.
You know this already, but it's worthwhile repeating: the const
qualifier is a directive to the compiler only. It has nothing whatever to do with anything you feel like doing at run time. The sense of const
is: "hey, mr. compiler: tell me whenever you notice that I modify this variable in a way that I don't mean to." AFAIK, the compiler issues a warning when it sees such self-destructive usage. I suppose you might be able to get the compiler to issue a flat-out error in this case.
Yes it is perfectly valid.
A const char *
means the content the pointer points to is constant, but it doesnt stop the pointer from being assigned to another pointer because this doesn't change the content pointed to by the original pointer.
This gives you two pointers pointing to same memory location.
|----------|
| c1 |
| | 1000
| 2000 |
|----------|
|
|
|
|
-------------------->|----------|
| num |
-------------------->| | 2000
| | 2 |
| |----------|
|
|
|----------|
| c2 |
| | 3000
| 2000 |
|----------|
You can hack around and modify the content of a const char *
pointer but note that modifying a variable declared as const results in Undefined Behavior.
精彩评论