const char, char const

Hi! simple question

is this:
char const* str1 = "str1";

the same as:
const char* str2 = "str2";
?

I believe it is since whenever I try to do
str1[0] = 'A';
or
str2[0] = 'A';
I get the exact same error, namely "you cannot assign to a variable that is const"
I just want to make sure

Thank you!




Yes, it's the same.
Thank you!!!

also, How would you declare a pointer to a constant pointer to a char?

tricky one. I was thinking

char* const* str;
That's correct as well.
When you declare a variable 'const' it means you cannot change it.

1
2
3
4
char *x = "Zoo";
const char *z = "Moo";
x[0] = 'M'; // ok
z[0] = 'Z'; // will generate error because it's declared constant 



1
2
char *x = "Zoo";
x[0] = 'M'; // ok 

That's not ok either. It's undefined behavior, because "Zoo" is a constant array.
Well don't I feel sheepish. I have never come across the desire or need to actually do what I posted but you are right... although it did compile and run (and even printed out "Moo" before the segfault) it was obviously wrong. I suppose I figured that somehow there was an implicit conversion that dealt with the const-ness of assigning a string literal. Thanks for the lesson.
There is such an implicit conversion (although it's deprecated).
That's why it's dangerous - due to that, it compiles, when it actually shouldn't.
Really?? so then how would you initialize a pointer to a variable char???
is it possible to initialize a pointer to a char so that it points to "something" after the declaration-initialization?
And in C++11 there is no such implicit conversion.
1
2
3
4
char *var;
var = new char[7];
strcpy(var,"foobar");
delete [] var;


EDIT: ouch I must be asleep today =/
Last edited on
Warning: delete is used improperly, a memory leak will occur.
Topic archived. No new replies allowed.