Go Down

Topic: Assiging contents of one array to another? (Read 807 times) previous topic - next topic


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:
Code: [Select]
void sendMsg(byte msgString[])
and then call it like this:
Code: [Select]

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?



Apr 30, 2009, 09:39 am Last Edit: Apr 30, 2009, 09:46 am by interlol Reason: 1
Try this on your computer, not in the Arduino but it's the same language:
Code: [Select]
#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!
Code: [Select]
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 ;)


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

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131