Home > Net >  Put an array in the end of another array C
Put an array in the end of another array C

Time:09-11

Normally it's a question about a buffer with a null-terminated string, but we can extrapolate it to a general case.

I have a big array of a fixed length, let's say 10:

char outputArray[10] = {'-','-','-','-','-','-','-','-','-','-'};

And I have some other (Edited: smaller) array (in my case it's a char buffer with null terminator) with a variable length. Let's say it's a buffer of 6 elements, but the actual length is indicated by another variable.

char inputArray[10] = {'h','i','/0',...some other values, i'm not interested in};
int arrLength = 2; // For my task it means a strlen(inputArray);

How to put a small array at the end of a big array, to get this:

outputArray = {'-','-','-','-','-','-','-','-','h','i'} // the null terminator isn't important, it's not about the strings, it's about arrays.

Constraints:

  • I can't use std, so only "native" solutions (it's for Arduino)
  • C 11
  • Code should be memory and time efficient (some elegant algorithm without too much loops and too much temporary variables or calculations please)

Thank you in advance

Edited:

Thank to @ThomasWeller for an answer. I have a small precision though. What if I need to clean all the elements before the inserted array?

For example I had some garbage

{'a','k','$','-','n','"','4','i','*','%'};

And I need to get

{'-','-','-','-','-','-','-','-','h','i'};

Do I need 2 loops? First to reset an array and the second one to set the actual result?

CodePudding user response:

It can be done with a single for loop and a single variable:

  for (char i=0; i<arrLength; i  )
  {
    outputArray[10-arrLength i] = inputArray[i];
  }

If you make arrLength a char instead of an int, this will even save you 2 bytes of memory ;-)

Use memset() to set all memory to an initial value and then memcpy() the contents at the end:

char output[10];
char input[10]  = "hi\0------";
char arrLength = 2;
void setup() {
  memset(output, '-', 10);  // "----------"
  memcpy(output 10-arrLength, input, arrLength);
  Serial.begin(9600);
  Serial.write(output, 10);
}
void loop() { }

Output in Arduino IDE

  • Related