在 C 中为 const char * 分配定义常量 [英] Assign a define constant to const char * in C
本文介绍了在 C 中为 const char * 分配定义常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不完全确定哪个是将常量分配给 const char *
的正确方法.两种方式都可以吗?
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);
推荐答案
opt1 = MSG1;
将分配指针opt1
指向MSG1
指向的字符串.
will assign the pointer opt1
to point to the string literal that MSG1
points.
strcpy(opt2, MSG1);
将MSG1
的内容复制到数组opt2
中.
will copy the contents of MSG1
to the array opt2
.
既然你把opt2
声明为const
,修改它的内容是非法的,所以第一种方式是正确的.
Since you are declaring opt2
as const
, it's illegal to modify the content of it, so the first way is correct.
这篇关于在 C 中为 const char * 分配定义常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文