Nick
Nick

Reputation: 3494

Adding two arrays?

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!

Upvotes: 4

Views: 900

Answers (2)

Steztric
Steztric

Reputation: 2942

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);
}

Upvotes: 2

P.P
P.P

Reputation: 121347

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 :)

Upvotes: 2

Related Questions