简体   繁体   English

多维C数组

[英]Multidimensional C Arrays

I have four arrays that contains some values. 我有四个包含一些值的数组。 Another array should contain all these four arrays like shown in the code: 另一个数组应包含所有这四个数组,如代码所示:

static const long ONE_COLOR[2] = { RGB_BLACK, RGB_WHITE };
static const long TWO_COLOR[4] = { RGB_WHITE, RGB_RED, RGB_GREEN, RGB_BLUE };
static const long THREE_COLOR[8] = { RGB_BLACK, RGB_RED, RGB_GREEN, RGB_BLUE,
    RGB_CYAN, RGB_YELLOW, RGB_MAGENTA, RGB_WHITE };
static const long FOUR_COLOR[16] = { RGB_WHITE, RGB_RED, RGB_GREEN, RGB_BLUE,
    RGB_CYAN, RGB_YELLOW, RGB_MAGENTA, RGB_DARK_RED, RGB_DARK_GREEN,
    RGB_DARK_BLUE, RGB_LIGHT_BLUE, RGB_LIGHT_GREEN, RGB_ORANGE, RGB_LIME,
    RGB_PINK, RGB_LILA };

//this array should contain all other arrays
static const long COLOR_ARRAY = {ONE_COLOR,TWO_COLOR, THREE_COLOR,
    FOUR_COLOR };

My problem is to access the values in the array. 我的问题是访问数组中的值。 I thought I can receive the value of RGB_BLACK with COLOR_ARRAY[0][0] . 我以为可以用COLOR_ARRAY[0][0]接收RGB_BLACK的值。 I tried it with some pointer constructions, but it doesn't work neither :( 我尝试了一些指针构造,但都没有用:(

It sounds like you want an array of pointers to arrays. 听起来您想要一个指向数组的指针数组。

static const long *const COLOR_ARRAY[4] = {
    ONE_COLOR, TWO_COLOR, THREE_COLOR, FOUR_COLOR
};

Both const are recommended: the first const means that this is a pointer to constant arrays, the second const means that this array of pointers is, itself, constant. 推荐两个const :第一个const表示这是指向常量数组的指针,第二个const表示该指针数组本身就是常量。

You can access the elements as you'd think, so COLOR_ARRAY[1][3] == RGB_BLUE , et cetera. 您可以按照自己的想法访问元素,因此COLOR_ARRAY[1][3] == RGB_BLUE等。

Note 注意

I am being a little sloppy with terminology. 我对术语有些草率。 You are not actually getting pointers to arrays but pointers to the first element in each array. 您实际上并不是在获取指向数组的指针,而是指向每个数组中第一个元素的指针。 For most operations, in C, an array and a pointer to the first element are interchangeable. 对于大多数操作,在C中,数组和指向第一个元素的指针可以互换。

Maybe you mean 也许你是说

static const long COLOR_ARRAY[] = {ONE_COLOR,TWO_COLOR, THREE_COLOR, FOUR_COLOR };

You don't have [] in your version. 您的版本中没有[]

you can define COLOR_ARRAY like this: 您可以像这样定义COLOR_ARRAY:

static const long* COLOR_ARRAY[4] = {ONE_COLOR,TWO_COLOR, 
                                     THREE_COLOR,FOUR_COLOR };

now you should be able to use: 现在您应该可以使用:

COLOR_ARRAY[0][0]

You can combine arrays like this: 您可以像这样组合数组:

first[3] = { 11, 17, 23 };
second[3] = { 46, 68, 82 };

combo[2][3] = {
         { 11, 17, 23 },{ 46, 68, 82 }};

I shamelessly copied this example from here: http://rapidpurple.com/blog/tutorials/c-tutorials/programming-in-c-array-of-arrays/ 我从这里无耻地复制了此示例: http : //rapidpurple.com/blog/tutorials/c-tutorials/programming-in-c-array-of-arrays/

Check it out! 看看这个!

Best regards -Tom 最好的问候-汤姆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM