1

I am an absolute newbie to Arduino and C++ and try to go through some tutorials to gain a minimal insight. However I stuck already at some tiny Points. What I want to do? Merge two 8 bit integer Arrays in to one 16 bit Array:

int summand_one[8] = {0,0,0,1,1,0,0,0};
int summand_two[8] = {1,0,0,0,0,0,0,1};

int * summand = new int[16];
std::copy(summand_one, summand_one+8, summand);
std::copy(summand_two, summand_two+8, summand+8);

The result should be

{0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1}

However it's not working at all. Constructor/destructor/type errors…

Any helpful idea how to do this?

  • 1
    If you get errors, please include them into your question. They are normally very helpful – chrisl Aug 14 at 11:13
1

It's better to avoid dynamic memory allocation on an Arduino, with only 2 KB of SRAM memory.

Note that your arrays cost 2 (bytes/int) * (8 + 8 + 16) = 64 bytes. And it seems you are only storing booleans, which could be stored in one bit. So consider another alternative (I will not work that out, since maybe memory consumption is not a problem).

However, an easy solution is to use uint8_t.

Also, I would use a simple memcpy. Very naively it would look like:

uint8_t summand_one[8];
uint8_t summand_two[8];
uint8_t summand[16];

void setup()
{
}

void loop()  
{ 
  memcpy(summand, summand_one, 8);
  memcpy(summand + 8, summand_two, 8);
}

Using some constants for the sizes, you get more flexible/readable and maintainable code:

static const uint8_t SummandOneSize = 8;
static const uint8_t SummandTwoSize = 8;

uint8_t summand_one   [SummandOneSize];
uint8_t summand_two   [SummandTwoSize];
uint8_t summand_merged[SummandOneSize + SummandTwoSize];

void setup()
{
}

void loop()  
{ 
  memcpy(summand_merged                 , summand_one, SummandOneSize);
  memcpy(summand_merged + SummandOneSize, summand_two, SummandTwoSize);
}
  • Thanks, that did it. Also thanks for the extra explanation on the dynamic memory allocation! – Nikolaij Aug 14 at 12:18
  • You're welcome. – Michel Keijzers Aug 14 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.