Pages: [1]   Go Down
Author Topic: Assiging contents of one array to another?  (Read 531 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 29
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

0
Offline Offline
Newbie
*
Karma: 0
Posts: 27
Arduino rocks
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Try this on your computer, not in the Arduino but it's the same language:
Code:
#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
    sendMsg(things);
}
The program will print the same address!
Code:
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 smiley-wink
« Last Edit: April 30, 2009, 02:46:09 am by interlol » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 29
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: