指定一个常量定义在C为const char * [英] Assign a define constant to const char * in C

查看:162
本文介绍了指定一个常量定义在C为const char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能完全肯定这是分配恒定为为const char * 的正确方法。有两种方式好吗?

 的#define MSG1我的消息#1
#定义MSG2我的消息#2
#定义MSG3我的信息#3为const char * OPT1 = NULL;
为const char OPT2 [20];开关(N){
    情况1:
        OPT1 = MSG1;
        //或者它应该是:
        的strcpy(OPT2中,MSG);
    打破;
    案例2:
        OPT1 = MSG2;
        //或者它应该是:
        的strcpy(OPT2,MSG 2);
    打破;
    案例3:
        OPT1 = MSG3;
        //或者它应该是:
        的strcpy(OPT2,MSG3);
    打破;}
// ...
的printf(%S,OPTX);


解决方案

  OPT1 = MSG1;

将分配指针 OPT1 指向字符串的 MSG1 分。

 的strcpy(OPT2中,MSG);

MSG1 的内容复制到阵列 OPT2

由于您声明 OPT2 常量,这是非法修改它的内容,因此第一种方式是正确的。

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;

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.

这篇关于指定一个常量定义在C为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆