CyrielN
CyrielN

Reputation: 99

C++/Arduino Passing pointer to 2D array stored in PROGMEM to a function

I have several const int 2D arrays globally stored in PROGMEM. for example:

const int image1[][17]PROGMEM = {
  {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0},
  {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0},
  {1,1,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0},
  {1,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0},
  {1,1,1,0,0,0,1,1,1,0,0,1,1,1,1,0,0}
}

I would like to read out this 2d image array in a function. Which image to read out should be specified in the argument.

void printImage(image)
{
  // do something with element i,j of image
  pgm_read_byte(image[i][j])
}

I am not very expierenced with the use of pointers etc. but I know that's the way to do it. Can you show me how to make it work?

How I do it now; I have the function printImage1() without any arguments, and in the body function I use:

pgm_read_byte(&image1[i][j])

to read out image1. For image2, image3 etc. I copy the function printImage1 and change imgage1 from above to image2, image3 etc. This is redundant programming thats why I want to specify the image in the argumant using only one function printImage.

Upvotes: 2

Views: 1659

Answers (1)

AnArrayOfFunctions
AnArrayOfFunctions

Reputation: 3754

Easily - by using array reference:

void printImage(const int (&image)[5][17])
{
    // ...
}

If you want the array being passed to be always with the size of 5 x 17. Else you can use a pointer to it's first element:

void printImage(const int (*image)[17])
{
    // ...
}

Upvotes: 4

Related Questions