[ell-i-developers] Re: Initializing a typedef struct inside a typedef struct

  • From: Pekka Nikander <pekka.nikander@xxxxxx>
  • To: ell-i-developers@xxxxxxxxxxxxx
  • Date: Sat, 10 May 2014 07:42:07 +0300

> typedef struct {
>     uint8_t  optionLength;
>     uint8_t *optionValue;
> }CoapOption;
> 
> typedef struct  {
> CoapOption uriPath;
> CoapOption uriQuery;
> CoapOption contentFormat;
> CoapOption accept;
> }CoapOptions;
> 
> typedef struct
> {
>   uint8_t* token;
>   CoapOptions options;
> }CoapMsg;

I presume you are using C, not C++, and especially not C++11 which is better in 
type inference.

> 
> When I do:
> CoapOptions options = { { 0, NULL }, { 0, NULL }, { 0, NULL }, { 0, NULL } };

This is an initialisation.  

> CoapMsg* coapMsg;
> coapMsg->options = { { 0, NULL }, { 0, NULL }, { 0, NULL }, { 0, NULL } };

This is an assignment.

There are different rules for initialisation and assignment in C (and C++).

In the first case, you are initialising the struct.  In the latter case, you 
are trying to assign a constant value to the options field in the CoAPMsg 
struct.  The options field there is a struct itself.  In that case, C is not 
able to do type inference; that is, it is not able to determine what type the 
right hand side should be, and therefore it is not able to convert the compound 
initialiser into an object of the CoapOptions type.  

In the assignment case, you can use a C99 compound literal on the right hand 
side.  See the following question in stackoverflow for more info:

http://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-ansi-c

If you were using C++11, IIRC the compiler should be able to do type inference 
and your code might work.  But I'm not sure.


Now, taking a step back, if you want your CoAPMsg to be binary compatible with 
the actual protocol messages, it simply won't work, I'm sorry.  

For a temporary, still-not-very-good that actually works for parsing the 
options, see

https://github.com/Ell-i/Runtime/blob/feature-coap-temp/stm32/libraries/CoAP/coap_input.c

I don't remember having written code that encodes options, yet, but you need to 
have code for that too, due to the delta encoding used.

--Pekka


Other related posts: