Go Down

Topic: Array initialisation in a class (Read 737 times) previous topic - next topic

ardudillo

Jun 15, 2010, 05:44 pm Last Edit: Jun 15, 2010, 05:45 pm by ardudillo Reason: 1
Hello forum, I was trying to write a quick and dirty ring buffer and have run into the following problem, I 'm not too sure what happens when I try to declare an array as a member of a class but initialise it in a constructor, e.g.

Quote

class myRingBuffer {
  public:
  
  int daBuffer[];
  
  myRingBuffer(int size) {
    daBuffer[size];
  }
};


void setup() {
  myRingBuffer mrb = myRingBuffer(10);
  mrb.daBuffer[9] = 3;
  Serial.begin(9600);
  Serial.println(mrb.daBuffer[9]);
}

void loop() {
}



So, the above compiles, uploads and prints 3 on the serial monitor. But is it doing what I assume it is doing, that is creating a 10 integer long array when the constructor gets called? Or does the single line in the constructor simply call an address "size" integers down from the start of the array and discard the result? What I 'm driving at is, when I read/write to the array after I instantiate "mrb" am I using a legal address or am I groping at random somewhere in memory?

One final worry, when trying to encapsulate stuff to keep things tidy, is there any worthwhile performance difference if using typedef and data structures instead of C++ classes?

AlphaBeta

You can use template programming for solving this: http://alexanderbrevig.googlecode.com/files/SimpleFIFO_1-2.zip
:)

lloyddean

The for-loop in the 'setup' fucntion of that HelloSimpleFIFO.pde example will not produce the results you're probably expecting  and should probably replaced with a while-loop as follows:

Code: [Select]

void setup() {
 Serial.begin(9600);
 
 SimpleFIFO<int,10> sFIFO; //store 10 ints
 
 sFIFO.enqueue(1);
 sFIFO.enqueue(2);
 sFIFO.enqueue(3);
 sFIFO.enqueue(4);
 sFIFO.enqueue(5);
 
 Serial.print("Peek: ");
 Serial.println(sFIFO.peek());
 
 while ( sFIFO.count() ) {
   Serial.print("Dequeue ");
   Serial.println(sFIFO.dequeue());
 }
}


ardudillo

Thanks guys, I 'll check out FIFO. However, can you let me know if the code I posted does what I thought it does or if it's a horrible monstrosity?

Go Up