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 ..
p2
由字符串文字初始化,即它是字符串文字的副本 ,因此p2
为非const
可以:
char p2[]="myGood";
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! ^^)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.