0

I've got a class called Engine which holds and returns a buffer like so:

template <int width, int height, int meshSize>
class Engine {
    public:
        byte buffers[2][width][height];
        byte fBuffer = 0;
        byte** getBuffer() {
            return buffers[fBuffer];
        };
}

and I want to loop through the values in my main, but I can't seem to get it working..

byte* buff;

// main
buff = engine->getBuffer();

for (int x = 0; x < 320; x++) {
    for (int y = 0; y < 320; y++) {
        if (buff[x][y] != NULL) {
            Serial.println(buff[x][y]);
        }
        // lcd.drawPixel(x, y, RGB(buff[x][y], buff[x][y], buff[x][y]));
    }
}

What combination of asterisk and/or parenthesis will work?

Nathan Prins
  • 383
  • 1
  • 4
  • 16
  • I don't see `fBuffer` declared. Although an array decays into a pointer, an array of arrays does not decay to a pointer to pointer. – aschepler Apr 07 '17 at 00:18
  • Sorry! I've added the missing line. It's just a `byte` which contains the index of the current 'front' buffer – Nathan Prins Apr 07 '17 at 00:21

1 Answers1

0

You should return a reference to your array, rather than a pointer. I also recommend providing a const overload of getBuffer for read-only operations.

template <int width, int height, int meshSize>
class Engine {
public:
    using BufferType = byte[width][height];

    BufferType const& getBuffer() const {
        return buffers[fBuffer];
    };

    BufferType& getBuffer() {
        return buffers[fBuffer];
    };

private:
    BufferType buffers[2];
    byte fBuffer = 0;
};

You can use auto to deduce this type when calling getBuffer for brevity:

auto& buff = engine->getBuffer(); // reference to the buffer
Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38
  • Thanks for the response! This gives me a whole set of errors: `Engine.h: 18:9: error: expected nested-name-specifier before 'BufferType using BufferType = byte[width][height] Engine.h: 18:9: error: using-declaration for non-member at class scope` and more.. I should mention this is compiled with Visual Micro for an Arduino Uno. – Nathan Prins Apr 07 '17 at 00:39
  • @NathanPrins It looks like you are compiling for C++98. Maybe you can check this post for instructions on how to compile for C++11 (or even better, C++14). http://stackoverflow.com/questions/16224746/how-to-use-c11-to-program-the-arduino Alternatively, you can use this syntax for C++98 (though I would highly recommend not using a version of C++ that is almost 20 years out of date) `typedef byte BufferType[width][height]` – Joseph Thomson Apr 07 '17 at 00:49
  • Just you wait for the telepathic compiler in C++ 2143 . – user4581301 Apr 07 '17 at 01:42