在C中我可以声明一个常量字符数组吗?

时间:2011-10-03 02:58:12

标签: c arrays character

我正在处理一个字符串,表示符号的变化。我已成功使用下面注释掉的字符串,但更喜欢使用常量字符数组UP =“up / 0/0”和DOWN =“down”的简单if-else语句。

有没有人知道一种简单的方法来声明这样的常量值?

    char direction[5]; // declares char array to signify sign change    
    if (value - price1 > - 0.005) { // adjusts for noise near 0
        direction = UP;
    }
    else direction = DOWN;

    // update price-change direction string
//      if (value - price1 > - 0.005) { // adjusts for noise near 0
//          direction[0] = 'u';
//          direction[1] = 'p';
//          direction[2] = 00; // set character to null value
//          direction[3] = 00;
//      }
//      
//      int[4] var_name 
//      else {
//          direction[0] = 'd';
//          direction[1] = 'o';
//          direction[2] = 'w';
//          direction[3] = 'n';
//      }

3 个答案:

答案 0 :(得分:4)

如果您以后没有修改字符串,可以这样做:

const char *direction:
if (value - price1 > - 0.005) { // adjusts for noise near 0
    direction = UP;
}
else
    direction = DOWN;

答案 1 :(得分:1)

你不能这样分配,但你可以这样做:

strcpy(direction, UP);

strcpy(direction, DOWN);

显然,小心不要溢出缓冲区。如果这些是唯一可能的来源,那你很好。

答案 2 :(得分:1)

考虑使用:

const char up_string[] = "UP";
const char down_string[] = "DOWN";
char *direction;
direction = (value - price1 > - 0.005) ? up_string : down_string;

然后,您可以将方向简单地指向其中任何一个位置(而不是使用strcpy)。

相关问题