char const * — string OR ptr-to-single-char?#my take

see also my blog – http://bigblog.tanbin.com/2011/09/qq-char-reflex.html
see http://www.codeguru.com/forum/archive/index.php/t-227977.html and http://cboard.cprogramming.com/c-programming/106063-difference-between-const-char-*-char-const-*.html

First thing first — q(const char*) is better written as q(char const *) which reads left-to-right “non-const pointer to const char”

Q: If this is a common C-string, is the entire string const? Some say The const is on the first char only.
%%A:You can advance this (non-const) pointer through an array of chars, but you can’t edit _any_ of the chars using this (const!) pointer – like changing ‘X’ to ‘Y’.
 
Q: Do we need to explicitly remove constness of a q(char const *)?
A: Yes. Constness radiates left. Use const_cast to remove const
A: I saw this in the Macqurie coding test.

char const * ptr
– often used to represent a c-string, but technically a pointer to a single char. The real thing in memory could be a char-array or could be a single char. You can’t tell. If you don’t know the length of the array, then you don’t know where the array ends, even if there’s a continuous stream of 9999999999 chars.
– This pointer can’t be used to state-edit the char, but the char is possibly state-editable by other pointers.

Q: how long is this c-string?
A: you can’t tell. The original thingy
– could be a single char + null
– could be a single char without a null
– could be nothing but the null char
– could be a regular null-terminating c-string
– could be a bunch or chars without a null. This ptr may advance forever without a null character.
– or this pointer may point to a heap location already deallocated – dangling pointer
– or this pointer may be uninitialized

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s