Operating System - HP-UX
1820260 Members
2893 Online
109622 Solutions
New Discussion

read struct from unsigned char [5000] in c program

 
Xiaoming Zhang
Contributor

read struct from unsigned char [5000] in c program

Hi,

I produced an array of unsigned char and the array contained binary data. I used to write the data back into a disk file and then read the file into a struct variable. Is there anyway I could directly read data from the array into the struct variable without writing and reading of a disk file?

Thanks.

Xiaoming
1 REPLY 1
Sam Nicholls
Trusted Contributor

Re: read struct from unsigned char [5000] in c program

There are a couple ways to do this depending on if you really want to copy the data into the new structure, or if you want to access the char array via a structure pointer.

1) Copy data into new structure

unsigned char arr[5000];
struct foo foo_struct;

memcpy((void *) &foo_struct, (void *) arr, sizeof(foo_struct));

Now, foo_struct has the same binary data as arr.

2) Access array data via structure pointer.

unsigned char arr[5000];
struct foo *foo_ptr;

foo_ptr = (struct foo *) arr;

Now, you can access the foo struct pointed to by foo_ptr...

foo_ptr->member1;
foo_ptr->member2;
...

-sam