gonadgranny:
Hi folks. I am trying to pass an array to a class constructor but run into trouble when i try to assign them.
I have read that in C you cannot assign arrays and must use pointers instead. I have tried using the * operator and managed to compile my program but it doesn't work as it should.
If anyone could point out where I am going wrong that would be great. Thanks, Danny.
class Motion {//class to encapsulate the functionality required to play a motion
byte *xMotion;//byte arrays
byte *yMotion;
byte s;//size of byte arrays
public:
Motion(byte xMotion_[], byte yMotion_[], byte s_) {//pass the arrays containing the x and y motions and the sizes thereof
xMotion = xMotion_;
yMotion = yMotion_;
s = s_;
}
passing a pointer to the array which the class instance will be using is workable.
what is your problem, exactly? Perhaps create a member function that simply traverses and prints the values in your arrays, to make sure you are happy with the data.
(Remember that you can use pointer arithmetic to traverse arrays.)
Example:
class Motion {
byte *xMotion;//byte arrays
byte s;//size of byte arrays
public:
Motion(byte xMotion_[], byte s_){xMotion = xMotion_; s = s_;};
void printArray(){byte* ptr = xMotion; for(int i = 0; i < s; i++) {Serial.println(*ptr++);}};
};
byte myArray[] = { 255, 0, 125, 0, 255};
Motion motion(myArray, sizeof(myArray)/sizeof(myArray[0]));
void setup()
{
Serial.begin(9600);
motion.printArray();
}
void loop()
{
}
(I still think you would be happier putting those two arrays into a struct that contained the x and y positions
)
Edit: like this:
struct Data{
byte x;
byte y;
};
class Motion {
Data *xMotion;//byte arrays
byte s;//size of byte arrays
public:
Motion(Data xMotion_[], byte s_){xMotion = xMotion_; s = s_;};
void printArray(){
Data* ptr = xMotion;
for(int i = 0; i < s; i++)
{
Serial.print(ptr->x);
Serial.print(",");
Serial.println(ptr++->y); //looks weird, right?!
//Serial.println(ptr->y); // alternate approach for readability
//ptr++
}
};
};
Data data[] = {
{255, 0},
{125, 255},
{255, 125}
};
Motion motion(data, sizeof(data)/sizeof(data[0]));
void setup()
{
Serial.begin(9600);
motion.printArray();
}
void loop()
{
}