c - changing a const char *str1 = "abc" -



c - changing a const char *str1 = "abc" -

is practice? code compiles , runs wonder if practice emulate in c code,

we write const char *str1 = "abc"; then later, lets there pointer variable char *str2 points dynamically allocated memory and str1 = str2 both str1 , str2 point dynamically allocated memory

so have lost track of pointer "abc". though in code, may not need wonder best recommended way handle these.

the overall problem need string declared abc , later dependent on user input, may want utilize string supplied user.

it's absolutely fine. const char *str1 means "a pointer can modified, character info cannot modified (through pointer)".

so, can point str1 @ string like, , makes sense "reseat" point @ different strings @ different times.

obviously if code complicated enough, can create hard reader work out variable contains, that's true of variables. illustration want careful pointers point @ string literals , point @ dynamically-allocated memory, because might not clear whether pointer should freeed.

if wanted str1 point @ same string, define const char * const str1 (or char const *const str1 in order create position of const consistent). that's not want in case, , fact haven't declared str1 const indicates much reader.

c string char

Comments

Popular posts from this blog

javascript - mongodb won't find my schema method in nested container -

Hibernate criteria by a list of natural ids -

ios - Lagging ScrollView with UIWebview inside -