2015-03-13 50 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]);