4

In the Arduino IDE, I'd like to add the contents of two existing arrays like this:

#define L0 { {0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 0, 0} }
#define L1 { {0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0, 0} }

should become

   int myarray[3][4] = { {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 0} }

How would I go about this?

Thanks!

5
  • 3
    Have you tried using a loop or two? Commented Oct 12, 2012 at 19:21
  • 3
    wrap the array in a class, initialise the content in the constructor, and create a function with a static instance variable of the class, return a reference to the wrapped array Commented Oct 12, 2012 at 19:21
  • 1
    @lurscher -- So simple! Why didn't I think of that?? Commented Oct 12, 2012 at 19:22
  • 1
    (Nick, he's kidding. This is an incredibly simple problem.) Commented Oct 12, 2012 at 19:23
  • 1
    @lurscher - The correct answer is clearly Array(L0)+Array(L1). How you implement the Array class is an exercise for the reader :). Commented Oct 12, 2012 at 19:52

2 Answers 2

2

Thy this;

const int a[3][4] = { {0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 0, 0} };
const int b[3][4] = { {0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0, 0} };

int c[3][4];

const int* pa = &a[0][0];
const int* pb = &b[0][0];
int* pc = &c[0][0];

for(int i = 0; i < 3 * 4; ++i)
{
    *(pc + i) = *(pa + i) + *(pb + i);
}
Sign up to request clarification or add additional context in comments.

Comments

2

I think you are confused about how to go access the arrays L0 and L1 since they are defined as macros. Just assign them to arrays since the preprocessor will simply replace them:

int l[][4]=L0;
int m[][4]=L1;

Preprocessor will replace L0 and L1 with their values and compiler will only see them as:

int l[][4]={ {0, 0, 0, 0}, {0, 0, 0, 1}, {0, 2, 0, 0} };
int m[][4]={ {0, 0, 0, 5}, {0, 0, 0, 6}, {0, 0, 7, 0} };

Now, you can use l & m to access the elements of array. Should easy enough from here to add two arrays :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.