簡體   English   中英

我可以在C中聲​​明一個常量字符數組嗎?

[英]In C can I declare a constant character array?

我正在研究一個字符串來表示符號的變化。 我已經成功使用了下面注釋掉的字符串,但是希望使用簡單的if-else語句,使用常量字符數組UP =“ up / 0/0”和DOWN =“ down”。

有誰知道聲明這種常數的簡單方法?

    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';
//      }

如果以后不修改字符串,可以這樣:

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

您不能這樣分配,但是您可以這樣做:

strcpy(direction, UP);

strcpy(direction, DOWN);

顯然,請注意不要溢出緩沖區。 如果只有這些可能,那么您就可以了。

考慮使用:

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

然后,您可以將direction僅僅是指向這些位置中的任意一個的指針(與使用strcpy相反)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM