Assign a define constant to const char * in C

白昼怎懂夜的黑 提交于 2019-12-22 18:23:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!