Assiging contents of one array to another?

Perhaps a stupid question....can I assign the contents of one array to another in one single line, or do I need to do it position by position in a loop?

I've got a program with a dozen or so arrays, and at various points I need to serial.print the contents of those arrays, and I'm trying to simplify this to a single function, rather than have to repeat the code a dozen times.

So, can I declare the function like this:

void sendMsg(byte msgString[])

and then call it like this: sendMsg(array_name_here)?

Will that plug the entire contents of the array in as the contents of msgString, or not? If not, is there another way to do this easily/efficiently?

Thanks, Andy

Try this on your computer, not in the Arduino but it’s the same language:

#include <cstdio>
typedef unsigned char byte;

void sendMsg(byte msgString[])
    // print the address of the things, is it a copy? no, it's just a pointer!
    printf("Address of the array in sendMsg: %x\n", msgString);

int main()
    byte things[20];

    // first test: print the address of things
    printf("Address of the array in main: %x\n", things);

    // second test

The program will print the same address!

Address of the array in main: bffff70c
Address of the array in sendMsg: bffff70c

In reality, when you declare void sendMsg(byte msgString[]), msgString is a pointer to the array sent as a parameter of the function, nothing is copied, but all the values are accessible in your function because it’s the original array address that is being given.

Be very careful though: the C and the C++ do not keep the “length” of the array (given as a parameter, or inside the main function), you have to know it, otherwise you’ll get a buffer overflow somewhere.

To conclude:

  • there is no copy (or it has to be explicite with functions like memcpy)
  • you have to be careful not to access values outside the array (keep the length, and the largest index is (length-1))
  • this was not a stupid question, it’s actually a problem for a lot of programmers :wink:

Great, I was hoping it'd be that simple, but didn't know enough to be sure! Thanks :-)