[C++] Variable array length has strange behavior


hi all,

i don't understand why following code isn't working:

code: [select]

// byte collectormodulenumber = 2;

byte* responsebuffer = new byte[2 * collectormodulenumber];

for (byte = 0; < collectormodulenumber; i++)
{
// getid() return const word
serial.print(collectormodules[i]->getid()); // doesn't print nothing

const word moduleid = collectormodules[i]->getid();

if (i == 0)
{
responsebuffer[i] = highbyte(moduleid); // doesn't assign nothing
responsebuffer[i + 1] = lowbyte(moduleid);
}
else
{
responsebuffer[i + 1] = highbyte(moduleid);
responsebuffer[i + 2] = lowbyte(moduleid);
}
}


edit:
complete code:

collectormodule.h
code: [select]

class collectormoduleclass
{
 protected:
  static const word id = 1;

const word getid() { return id; };
};


mytest.h
code: [select]

class mytestclass
{
 protected:
collectormoduleclass* collectormodules[];
byte collectormodulenumber;

mytestclass(const byte& collectormodulenumber);

void sendmanifest();

void registercollector(const byte& i, collectormoduleclass* cm);
};


mytest.cpp
code: [select]

#include "mytest.h"

mytestclass::mytestclass(const byte& collectormodulenumber)
{
this->collectormodulenumber = collectormodulenumber;
};

void mytestclass::registercollector(const byte& i, icollectormodule* cm)
{
collectormodules[i] = cm;
};

void mytestclass::sendmanifest()
{
byte* responsebuffer = new byte[2 * collectormodulenumber];

for (byte = 0; < collectormodulenumber; i++)
{
// getid() return const word
serial.print(collectormodules[i]->getid()); // doesn't print nothing

const word moduleid = collectormodules[i]->getid();

responsebuffer[2 * i] = highbyte(moduleid); // doesn't assign nothing
responsebuffer[2 * + 1] = lowbyte(moduleid);
}
};


sketch.ino
code: [select]

#include "collectormodule.h"
#include "mytest.h"

collectormoduleclass* c1 = new collectormoduleclass();
collectormoduleclass* c2 = new collectormoduleclass();
mytestclass* m = new mytestclass(2);

void setup()
{
m->registercollector(0, c1);
m->registercollector(1, c2);

m->sendmanifest();
}

void loop(){}

maybe because using bytes 0 , 1 entry 0, bytes 2 , 3 entry 1, bytes 3 , 4 entry 2...  each entry past 1 overlaps overlaps previous entry.

try:
code: [select]
  responsebuffer[2*i] = highbyte(moduleid);
 responsebuffer[2*i + 1] = lowbyte(moduleid);


Arduino Forum > Using Arduino > Programming Questions > [C++] Variable array length has strange behavior


arduino

Comments

Popular posts from this blog

invalid use of void expresion in FlexiTimer2 library

error: a function-definition is not allowed here before '{' token

LED Strip Code