My OOP-style C++ application has a method (used in many .cpp files), that get two parameters: pointer to array and array size:
bool SendData(unsigned char* data, size_t size);
I have some arrays, that will never changes. And I want to define them, or make a consts, or something else, for doing this:
bool result1, result2;
unsigned char arr2[] = {0x2, 0x5, 0x6};
result1 = SendData(PREDEFINED_ARRAY_1, sizeof(PREDEFINED_ARRAY_1));
result2 = SendData(arr2, sizeof(arr2));
I try to solve it, using constants - just write in header file:
static const unsigned char PREDEFINED_ARRAY_1[] = {0x1, 0x3, 0x5};
static const unsigned char PREDEFINED_ARRAY_1[] = {0x2, 0x3, 0x4, 0x5, 0x6, 0x7};
But get compiler errors about '{' and '}'. It's confuse me, becouse I can write:
static const unsigned char c = 10;
And all will be ok. I can initialize variables, but can't init arrays? It's strange.
Yes, I know, that static variables should be initialized in cpp-files, but I have many files, that use this function with constants, so, as I know, It's a dead way. I show this code only to explain what I want.
Also I don't want to write something like this in constructor (or special function) after definition in class:
PREDEFINED_ARRAY_1[0] = 0x1;
PREDEFINED_ARRAY_1[1] = 0x3;
PREDEFINED_ARRAY_1[2] = 0x5;
Because the number of arrays is about 100 andlength ~20-30 symbols per each. Too many code for simple thing. Or not?
Then, I try to create special class:
class Array
{
public:
void Set(unsigned char symbol, ...); // using va_args
unsigned char* GetData();
size_t GetSize();
private:
unsigned char* data;
size_t size;
};
class MainClass
{
public:
MainClass();
void Send();
Array PREDEFINED_ARRAY_1;
Array PREDEFINED_ARRAY_2;
};
MainClass::MainClass()
{
PREDEFINED_ARRAY_1.Set(3, 0x1, 0x3, 0x5);
PREDEFINED_ARRAY_1.Set(6, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7);
}
void MainClass::Send()
{
SendData(PREDEFINED_ARRAY_1.GetData(), PREDEFINED_ARRAY_1.GetSize());
}
But in this case, I should manually count number of symbols. Maximum length may be about 50 symbols and the risk of mistake is to high. I want to avoid it.
Third and dumbest way is something like this:
#define PREDEFINED_ARRAY_1 {0x1,0x3,0x5}
int main()
{
unsigned char arr1[] = PREDEFINED_ARRAY_1;
SendData(arr1, sizeof(arr1));
}
But it is too ugly.
My question is: What the best practice for doing it?
P.S. As I already say, I'm using OOP paradigm and want to avoid global variables and other C-things.
SendDataaccept const data or make the array non-const... Otherwise you have constness problems.