Pages: [1]   Go Down
Author Topic: Array initialisation in a class  (Read 678 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Jr. Member
**
Karma: 1
Posts: 75
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
« Last Edit: June 15, 2010, 10:45:23 am by ardudillo » Logged

Norway@Oslo
Offline Offline
Edison Member
*
Karma: 13
Posts: 2033
loveArduino(true);
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Des Moines, WA - USA
Offline Offline
God Member
*****
Karma: 25
Posts: 779
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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());
  }
}
Logged

0
Offline Offline
Jr. Member
**
Karma: 1
Posts: 75
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

Pages: [1]   Go Up
Jump to: