Andy Lin
Andy Lin

Reputation: 447

variable-length array in struct with TI compiler in C (socket programming)

I'm writing code that dealing with data received from udp in application layer.

This is the function prototype used for receiving data from udp

int my_recv_UDP(int s,
                void* mem,
                int len,
                struct sockaddr* from,
                int fromlen);

in which it uses s as socket, puts data in mem with length len, and returns data length which's value might less then len.

For example

frameLen = my_recv_UDP(socket, rxBuf, 100, &ra, sizeof(ra));

in which it uses socket as socket, put data in rxBuf with length 100, and returns data length to frameLen.

Original data length might bigger or less then 100. Since you specify length value with 100, you might get data length less then 100 this time or loss data following order 100 next time, depending on frame.

I intended to create a data type by a struct and let this struct type's ptr to point to rxBuf.

i.e:

typedef struct{
    int cmd;
    int data[?];    //you don't know the data length until you receive data
    int len;
}rxBuf_s;

So, I can do like this.

rxBuf_s* rxBuf_p = rxBuf; 

With this, I can "manipulate" data in rxBuf easily, for example, if I want to read cmd into buffer:

int Cmd = rxBuf_p->cmd;

But I didn't know the data length until I receive it, I don't know what offset is len either, So decided to calculate the length in "run time" and put it in array, like:

typedef struct{
    int cmd;
    int data[length];    //length is calculated in run time.
    int len;
}rxBuf_s;

But VLA in struct is not allowed in C99.
How can I do? Is there any smart way to do this?

Upvotes: 0

Views: 129

Answers (1)

Klaus Gütter
Klaus Gütter

Reputation: 11997

So you receive cmd, data[length], len in this order in the frame. As you already noted, it is not possible to catch this 1:1 using a C structure. At least the len field has to be extracted by a different means, e.g.

length = ...; // calculate length

int cmd = *(int*)rxBuf;
int *data = (int*)rxBuf + 1;
int len = *(data + length);

Upvotes: 2

Related Questions