问题
I'm not entirely sure which is the right way to assign a constant to a const char *. Are both ways okay?
#define MSG1 "My Message #1"
#define MSG2 "My Message #2"
#define MSG3 "My Message #3"
const char *opt1 = NULL;
const char opt2[20];
switch(n){
case 1:
opt1 = MSG1;
// or should it be:
strcpy(opt2, MSG1);
break;
case 2:
opt1 = MSG2;
// or should it be:
strcpy(opt2, MSG2);
break;
case 3:
opt1 = MSG3;
// or should it be:
strcpy(opt2, MSG3);
break;
}
// ...
printf("%s", optX);
回答1:
opt1 = MSG1;
will assign the pointer opt1 to point to the string literal that MSG1 points.
strcpy(opt2, MSG1);
will copy the contents of MSG1 to the array opt2.
Since you are declaring opt2 as const, it's illegal to modify the content of it, so the first way is correct.
回答2:
Either will work (aside from the fact that opt2 should be declared without a const qualifier, since you're writing to the array with strcpy). The opt1 version is a bit more efficient, since it's just a pointer assignment, rather than a character-by-character copy.
回答3:
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest.
So strcpy(opt2, MSG3); will not be syntactically incorrect, but as opt2 is pointing to NULL, this will cause a segmentation fault (SIGSEGV).
On another note:
The compiler decides if strcpy(opt2, MSG3); will be lesser efficient than opt1 = MSG3; as most modern implementations are 'clever' enough not to .
@happydave is right, no const.
来源:https://stackoverflow.com/questions/20207688/assign-a-define-constant-to-const-char-in-c