PDA

View Full Version : casting a struct to char*


jhon
10-04-2004, 04:59 PM
Hi,

I wonder how to cast a char* to a struct.

I know the folowing way:


char *buffer;
struct X *x;

x = (X *)buffer;


but let's assume the following definition:


struct X
{
char a[100];
int n;


so, a will read all data until '\0' and then stop and no data will be read to variable n.

how can I fix it?

RobSeace
10-04-2004, 10:31 PM
Huh? I don't understand that question at all... Why would the
presence of a null char in the buffer cause the cast of it to a struct
to be unable to access fields beyond that null char?? That makes
no sense to me...

suraj
11-17-2004, 10:31 AM
With What i understood of the code u want to write is that u want to convert a char * to a struct type in such a way that the value of the char* can be received by all the struct members. U want to set the values of all the struct members with 1 char * . To do this easily in ur eg case declare the struct as


struct X{
int n;
char a[100];
};

by declaring the struct like this u can have the first 2 chars of the char* being assigned to n & the rest to a with a '\0' at the end of it.