正确的语法访问数组指针的值?

时间:2014-04-26 18:36:40

标签: c++ c arrays pointers arduino

(我意识到关于数据和指针的SO有很多问题和答案,但在涉及其中很多之后,我仍然没有得到它。)

问题:数组指针的正确语法访问值是什么?

背景:我正在做的事情很简单:我正在定义一些数组,然后定义一个指向那些数组的数组(下面的代码)。我这样做是为了让我可以在for..loop中引用我的'circle'数组。 (我意识到我可以通过定义一个多维数组来完全跳过指针,但为了便于编码和在这个阶段进行快速更改,将“圆”数组定义一次会很有帮助。)

当我尝试访问数组数据时,我遇到了问题。这符合但数据是垃圾:

for (int i = 0; i < circleArrayLength; i++) {

   for (int c = 0; c < 6; c++) {
    byte *index = circleArray[i][c]; // WRONG

    writeBufferSingle(basePattern[*index][0], basePattern[*index][1], 1);
   }
   writeScreen();
   delay(50);
}

那么,数组指针的正确语法访问值是什么?


byte circle0[7] = { 0, 1, 40, 44, 43, 42, 41 };
byte circle1[7] = { 1, 2, 39, 45, 44, 41, 40 };
byte circle2[7] = { 2, 3, 38, 46, 45, 40, 39 };
byte circle3[7] = { 3, 4, 37, 47, 46, 39, 38 };
byte circle4[7] = { 4, 5, 36, 48, 47, 38, 37 };


byte* circleArray[][7] = { circle0, circle1, circle2, circle3, circle4}

2 个答案:

答案 0 :(得分:1)

byte* circleArray[][7] = { circle0, circle1, circle2, circle3, circle4}

这几乎肯定是错的。 circleArray不应该是byte*的数组数组。

byte circleArray[][7] = { circle0, circle1, circle2, circle3, circle4};

...

byte index = circleArray[i][c];

writeBufferSingle(basePattern[index][0], basePattern[index][1], 1);

另外,请考虑storing circle<n> and circleArray in flash

答案 1 :(得分:0)

有两种方法可以做到。

方法一:

#include <stdio.h>

typedef char byte;

int main(void)
{
    byte circle0[7] = { 0, 1, 40, 44, 43, 42, 41 };
    byte circle1[7] = { 1, 2, 39, 45, 44, 41, 40 };
    byte circle2[7] = { 2, 3, 38, 46, 45, 40, 39 };
    byte circle3[7] = { 3, 4, 37, 47, 46, 39, 38 };
    byte circle4[7] = { 4, 5, 36, 48, 47, 38, 37 };

    byte *circleArray[] = { circle0, circle1, circle2, circle3, circle4};

    size_t circleArrayLength = sizeof(circleArray)/sizeof(circleArray[0]);

    for (size_t i = 0; i < circleArrayLength; i++) {
        for (size_t c = 0; c < 7; c++) {
            printf("circleArray[%zu][%zu] = %d\n", i, c, circleArray[i][c]);
        }
    }
}

方法二:

#include <stdio.h>

typedef char byte;

int main(void)
{
    byte circle0[7] = { 0, 1, 40, 44, 43, 42, 41 };
    byte circle1[7] = { 1, 2, 39, 45, 44, 41, 40 };
    byte circle2[7] = { 2, 3, 38, 46, 45, 40, 39 };
    byte circle3[7] = { 3, 4, 37, 47, 46, 39, 38 };
    byte circle4[7] = { 4, 5, 36, 48, 47, 38, 37 };

    byte (*circleArray[])[7] = { &circle0, &circle1, &circle2, &circle3, &circle4};

    size_t circleArrayLength = sizeof(circleArray)/sizeof(circleArray[0]);

    for (size_t i = 0; i < circleArrayLength; i++) {
        for (size_t c = 0; c < 7; c++) {
            printf("circleArray[%zu][%zu] = %d\n", i, c, (*circleArray[i])[c]);
        }
    }
}