2015-03-13 51 views
2

期望的行爲如何使用嵌套數組作爲函數中的值?

我想定義數組的數組,並訪問在函數頂層數組的值。

我已經試過

例如:

// the array 
char* myRGBColorArray[5][3] = { 
    {"0x00,","0x01,","0x02,"}, // i want to use this in a function 
    {"0x03,","0x04,","0x05,"}, 
    {"0x06,","0x07,","0x08,"}, 
    {"0x09,","0x10,","0x11,"}, 
    {"0x12,","0x13,","0x14,"} 
    }; 

// the function's format 
// cursor_set_color_rgb(0xff, 0xff, 0xff); 

// ideally i would like to use the indexed values, like this: 
cursor_set_color_rgb(myRGBColorArray[0]); 
cursor_set_color_rgb(myRGBColorArray[1]); // etc 

很新的C,因此仍然試圖讓我的周圍嵌套的數組頭,訪問索引值,並定義類型。

問題/ s的

  • 高於正確定義的myRGBColorArraytype
  • 如何正確訪問數組的索引值?

僅供參考,我在玩與周圍的功能是從第二個例子在這裏 - 它改變了光標的顏色:

https://stackoverflow.com/a/18434383

#include <stdio.h> 
#include <unistd.h> 

void cursor_set_color_rgb(unsigned char red, 
          unsigned char green, 
          unsigned char blue) { 
    printf("\e]12;#%.2x%.2x%.2x\a", red, green, blue); 
    fflush(stdout); 
} 

int main(int argc, char **argv) { 

    cursor_set_color_rgb(0xff, 0xff, 0xff); sleep(1); 
    cursor_set_color_rgb(0xff, 0xff, 0x00); sleep(1); 
    cursor_set_color_rgb(0xff, 0x00, 0xff); sleep(1); 
    cursor_set_color_rgb(0x00, 0xff, 0xff); sleep(1); 

    return 0; 
} 

回答

3

是myRGBColorArray的類型以上定義正確嗎?

排序。引用字符串文字時,應該使用const char*而不是char*

不過,從底部例子看來你想要的unsigned char的不是數組:

unsigned char colors[5][3] = { 
    {0x00, 0x01, 0x02}, 
    {0x03, 0x04, 0x05}, 
    {0x06, 0x07, 0x08}, 
    {0x09, 0x10, 0x11}, 
    {0x12, 0x13, 0x14} 
}; 

如何正確地訪問數組的索引值?

您可以編寫顏色的功能,例如:

void cursor_set_color_rgb(unsigned char color[3]) { 
    printf("\e]12;#%.2x%.2x%.2x\a", color[0], color[1], color[2]); 
    fflush(stdout); 
} 

,並設置顏色的第四顏色的排列像這樣的(記住,索引從0開始):

cursor_set_color_rgb(colors[3]); 

或者,您可以使用原始功能並像這樣使用它:

cursor_set_color_rgb(colors[3][0], colors[3][1], colors[3][2]);