Reputation: 476
I have two arrays in C++ and I'd like to append one to the end of the other such that:
char byte1[] = {0x00};
char byte2[] = {0x01};
Appending these two should yield {0x00, 0x01}. How would I do this? It's simple enough in Java using System.arraycopy(), but I'm not sure what library would help me to accomplish this in C++ / C as I'm coding for a microcontroller.
Upvotes: 2
Views: 12878
Reputation: 87516
Try using the string
class from the Arduino environment, which was meant to be used on AVR with the avr-g++ compiler. I am not sure if it supports having null (0) bytes, though.
http://arduino.cc/en/Reference/StringObject http://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/WString.cpp
Upvotes: 1
Reputation: 39354
If you're using C, you can do:
//Whatever sizes your stating arrays are.
const int S_ARR1 = 3;
const int S_ARR2 = 2;
//Create buffer that can hold both.
char combined[S_ARR1 + S_arr2];
//Copy arrays in individually.
memcpy(combined, byte1, S_ARR1);
memcpy(combined + S_ARR1, byte2, S_ARR2);
If you want C++, don't use the byte arrays in the first place. Use std::vector as it acts as an array that can track its own number of elements so you can feel more like you're in the java world :)
A little warning though about C++ Vector Memory for Embedded:
You're in a micro-controller, std::vector can waste alot of memory as it grows based on a multiple of current size. The more that's in it, the more you could be wasting. Having said that, it's a great class and as long as you know how it handles its memory its a great option.
Upvotes: 6
Reputation: 96167
You can't as you have written it there, C allocates fixed memory for those arrays to fit the size of the data you have initialised them with ie 1 byte
If you know how much data you are going to use you can initialise a larger array with char byte[10];
for 10 elements, but you can't automatically fill it at creation in C. If you don't know howmuch data you need until runtime then you need to allocate it with new (or malloc or c).
If you want java like behaviour look at std::vector, if your microcontroller support is
Upvotes: 1