7 years, 10 months ago.

dynaically generate a variable and put it into const unsigned char * parameter ?

hi. I'm trying to develop a mbed software using xbee.

My question is actually about C++ question, and not sure it's appropriate to raise it here.

Currently I am using a xbee lib and part of it is the following.

https://developer.mbed.org/users/yangcq88517/code/SmartLabXBeeAPI2/file/6e4ef3c302b4/SmartLabXBeeCore/Request/XBeeTx16Request.h

One of the parameters that a method 'setPayload' takes is 'const unsigned char *' I sort of understand that 'const' means one cannot change the value the pointer points to. But the values of payload in general change dynamically and so I need to somehow set the values to be flexible like

int num_char; unsigned char data[]; <- the error occurs here! num_char = sprintf(data, "{luminosity: %f3.2}", lum); tx16.setPayload(data, 0, num_char); 'tx16' is a XBeeTx16Request object

which raises an error:

Error: Incomplete type is not allowed in "main.cpp", Line: 45, Col: 20

Could anyone help me understand how to set the payload value properly and pass to the method?

1 Answer

7 years, 10 months ago.

In this situation the const in const unsigned char * means that the function can't change the data being pointed to. Since it's not a const in your code you can change it. That's not the cause of your bug.

use

<<code>>
...
<</code>>

to format your code correctly.

int num_char;
unsigned char data[]; <- the error occurs here!
num_char = sprintf(data, "{luminosity: %f3.2}", lum);
tx16.setPayload(data, 0, num_char); // 'tx16' is a XBeeTx16Request object

You can't create an array without specifying a size at creation time. An array is a pointer to a reserved block of memory, without setting a size the compiler doesn't know how much memory to allocate.

Give it a size that is large enough for the longest value you can expect (20 should be plenty) and it should be happy. To be safe use snprintf rather than sprintf, that will let you specify the maximum size of the output and prevent possible buffer overflow bugs if lum happens to be a massive number. Also in your printf you probably want %3.2f not %f3.2