pointer question

Consider the following code:

char s[] = "Hello";
const char* pc = s; // pointer to constant
pc[3] = 'g'; // error

My C++ book I'm reading says this is an error, because pc points to constant.

Does that mean constant variables can't change value? Therefore, by trying to assign pc[3] to 'g' we are trying to change the value of a constant variable which is illegal? Does that mean s is constant? What if the last line of code had been:

s[3] = 'g';

Would that be ok?

Matthew
Don't fillup the forums with the same question.
It is irritating and wastes people time.
No one has answered my question. Furthermore, I moved, because I thought this forum may be more appropriate for the question.

Cheers,
Matthew
No one has answered my question.


Umm... yeah I did?

http://cplusplus.com/forum/general/16401/
Your answer is wrong!
Look at my post
I'm 100% certain my answer is right.

Look at my post.

EDIT: blah I'll just baby step through it:

My C++ book I'm reading says this is an error, because pc points to constant.


Your book is right. You cannot change what pc points to because pc is a const char*.

Does that mean constant variables can't change value?


No. It means you cannot change a constant variable. The variable can still change by an outside source.

Therefore, by trying to assign pc[3] to 'g' we are trying to change the value of a constant variable which is illegal?


This is correct. You cannot do that. The compiler will error.

Does that mean s is constant?


No. You did not declare s as constant, so it is not constant.


What if the last line of code had been:


Then there would be no error.

Would that be ok?


Yes.
Last edited on
I don't want to split hairs, but the statement I was troubled by was:
const pointer means you cannot change what the pointer points to

This statement is true, but we we are not talking about a const pointer. If pc were a const pointer then it would be true that you could not change what the pointer points to and the following statement would be wrong:

pc = &someOtherCharVariable; // error pc is a const pointer

WHAT pc ACTUALLY IS
pc is a pointer to a char variable with the restriction that it can't change the char variable it is pointing to.

Cheers,
Dunson
Last edited on
Well I suppose it depends on your personal terminology.

"const pointer" vs. "pointer const"

When I say "const pointer" I refer to a non-const variable which is a pointer to a const variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int a, b;

//----------------

const int* cp = &a;  // the pointer itself is not const, what it points to is const

*cp = 0; // error
cp = &b; // ok

//-----------------

int* const pc = &a;  // the pointer itself is const, what it points to isn't

*pc = 0; // ok
pc = &b; // error 

Agreed
Topic archived. No new replies allowed.