I wasn't able to find a correct explanation on how to solve my problem.
I have a uint8_t array and I'm able to define it if I use this notation:
uint8_t array[] = {0x58, 0x01, 0x11, 0x00, 0x00, 0x00, 0x10, 0x7A};
However, if I use this other notation:
uint8_t array[8];
array[] = {0x58, 0x01, 0x11, 0x00, 0x00, 0x00, 0x10, 0x7A}
the compiler gives me an error:
error: expected primary-expression before ‘]’ token
How can I define my array later in my code after having initialized it?
EDIT 1:
I need to define the array inside the switch case like this:
uint8_t array[8];
switch(relay_on){
case 16: array[] = {0x58, 0x01, 0x12, 0x00, 0x00, 0x00, 0x10, 0x7B}; //
break;
}
and I need to use the array outside the switch. The array is not available outside the switch if I declare it inside the switch case.
EDIT2: use with std::array
std::array<uint8_t, 8> command1;
std::array<uint8_t, 8> command2;
switch(relay_on){
case 16: command1 = {0x58, 0x01, 0x12, 0x00, 0x00, 0x00, 0x10, 0x7B}; // switch on the relay 16
break;
}
switch(relay_off){
case 16: command2 = {0x58, 0x01, 0x11, 0x00, 0x00, 0x00, 0x10, 0x7A}; // switch off the relay 16
break;
}
int bytes_to_send1 = sizeof(command1);
int bytes_to_send2 = sizeof(command2);
int bytes_sent1 = 0;
int bytes_sent2 = 0;
do
{
n = send(sockfd, command1 + bytes_sent1, bytes_to_send1 - bytes_sent1, 0);
if ( n < 0 )
{
cerr << "Error writing to socket!" << strerror(errno) << endl;
close(sockfd);
}
bytes_sent1 += n;
}
while (bytes_sent1 < bytes_to_send1);
if I use the std::array notation, i get this error:
error: no match for ‘operator+’ (operand types are ‘std::array<unsigned char, 8>’ and ‘int’)
n = send(sockfd, command2 + bytes_sent2, bytes_to_send2 - bytes_sent2, 0);