I posted on this topic earlier but now I have a more specific question/problem.
Here is my code:
#include <cstdlib>
#include <iostream>
typedef struct{
unsigned int h;
unsigned int b[];
unsigned int t;
} pkt;
int main(){
unsigned int* arr = (unsigned int*) malloc(sizeof(int) * 10);
arr[0] = 0xafbb0000;
arr[1] = 0xafbb0001;
arr[2] = 0xafbb0011;
arr[3] = 0xafbb0111;
arr[4] = 0xafbb1111;
arr[5] = 0xafbc0000;
arr[6] = 0xafbc0001;
arr[7] = 0xafbc0011;
arr[8] = 0xafbc0111;
arr[9] = 0xafbc1111;
pkt* p = (pkt*) malloc(sizeof(int)*13);
p->h = 0x0905006a;
int counter;
Here's what I get for(counter=0; counter < 10; counter++) p->b[counter] = arr[counter];
p->t = 0x55555555;
std::cout << "header is \n" << p->h << std::endl;
std::cout << "body is" << std::endl;
for(counter=0; counter < 10;++counter)
std::cout << std::hex << *((p->b)+counter) << std::endl;
std::cout << "trailer is \n" << p->t << std::endl;
}
Here's what I get
header is
151322730
body is
55555555
afbb0001
afbb0011
afbb0111
afbb1111
afbc0000
afbc0001
afbc0011
afbc0111
afbc1111
trailer is
55555555
*(p->b) is replaced with the trailer! And if I remove the line where I assigned the trailer, that is p->t=0x55555555;, then the trailer and p->b are the same (afbb0000).
So my question is, how can I keep the structure define at the top the way it is and have this packet function properly.
EDIT:
I should be more clear. I writing this for a networking application, so I have to make a packet where the output is in this exact order, I am testing this by writing to a file and doing a hex dump. So my question really is:
How do I make a packet with a header, variable sized body, and a trailer always have this order? The only two solutions I can think of are having many different structures, or having a vector.
That is, I could structs where
typedef struct{
unsigned int h;
unsigned int b[12];
unsigned int t;
} pkt1;
typedef struct{
unsigned int h;
unsigned int b[102];
unsigned int t;
} pkt2;
etc
or I could do
std::vector<unsigned int> pkt (12);
pkt[0] = header;
pkt[1] = data;
...
pkt[2]= data;
pkt[11] = trailer;
I don't really like either of these solutions though. Is there a better way??
Also, this is somewhat of a separate question, I will have to do the same thing for receiving data. It is wise to do something like cast a block of data to a vector? I am going to be receiving the data as a void* and I will know the max length.