0

I know that following is bad programming practice

char * p1 = "myBad"  ;  

The above is bad as const "myBad" memory is getting pointed by non Const pointer . Compilers allow p1 as to support backward compatibility with C

IS the following a bad practice too ?

char p2[]="myBadORGood";

Whats the difference betweeen p1 and p2 . DOes compiler make a non-const copy for p2 ? I think i read somewhere that p2 is fine but not sure ..

4
  • The second is totally fine. You get an array with modifiable contents. The string literal is copied into the array on initialisation. Commented May 24, 2013 at 15:53
  • 2
    Note that it is no longer valid C++. Commented May 24, 2013 at 15:53
  • @chris .. you meant p2 is no longer valid ? if yes whats the best way Commented May 24, 2013 at 15:57
  • 1
    @MAG, p1, actually. C++11 disallowed char * pointing to string literals, and I'm very glad for it, as almost all cases of that were bugs. Commented May 24, 2013 at 16:01

2 Answers 2

3

p2 is initialized by the string literal, i.e. it is a copy of the string literal, so p2 being non-const is fine:

char p2[]="myGood";
Sign up to request clarification or add additional context in comments.

Comments

0

The first is not only bad practice but deprecated in C++ (C++03; according to chris' comment this is even illegal now in C++11).

The second is totally fine, the string literal is only used as a (read-only) "model" to initialize a new, independent array. Thus, the short

char arr[] = "abc";

is equivalent to the longer

char arr[] = { 'a', 'b', 'c', '\0' };

and can even be written like this:

char arr[4];
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
arr[3] = '\0';

(but don't write code like that! ^^)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.