Home > Blockchain >  Can I initialize a std::array<uint8_t with a string literal?
Can I initialize a std::array<uint8_t with a string literal?

Time:02-04

I write a lot of C code interacting with instruments using UART serial ports. I'm starting a new project where I'm trying to use a more object oriented approach with C . Here's how I've defined and sent commands in the past using C.

uint8_t  pubx04Cmd[] = "$PUBX,04*37\r\n";
HAL_UART_Transmit(&hUART1, pubx04Cmd, sizeof(pubx04Cmd), 5000); 

Which is pretty darn simple. C std::arrays have the size built in which seems kind of useful. But here's the only way I've figured out how to do it.

const char pubx04CString[] = "$PUBX,04*37\r\n";
std::array<uint8_t, 14> pubx04CPPArray;
std::copy(std::begin(pubx04CString), std::end(pubx04CString), pubx04CPPArray.begin());
HAL_UART_Transmit(&hUART1, pubx04CPPArray.data(), pubx04CPPArray.size(), 5000);

Which seems pretty clunky compared to the C way to do it.

  • Is there a cleaner way to do this using std::array?

  • Is there any real benefit to using std::arrays vs C arrays for this situation?

CodePudding user response:

std::array is an aggregate, i.e. a possible implementation may be like

template <typename T, size_t S>
struct array {
  T a[S];
  // ...
};

The enclosed array can be initializes as usual:

std::array<uint8_t, 14> pubx04Cmd{"$PUBX,04*37\r\n"};
  •  Tags:  
  • Related