Click to See Complete Forum and Search --> : about pointers & structure


serbet
April 28th, 2003, 08:26 AM
The are a lot of numeric variables, values of which changes often and often. Such as:

int a;
float b;
float c;

These values must be written to a file. I thought a shiny idea: If I declare a structure, items of which are a pointer to these variables, it would be better to work. Rather than writing the data variable by variable, I would write only the struct after every update of values. The struct is as the following:

typedef struct{
int* a;
float* b;
float* c;
}dat;

Only I must do is to assign the adresses of the variables to these pointers at the beginning of the program like this:

dat.a = &time;
dat.b = &pitch;
dat.c = &roll;

But when I do the following:

dat data;
fwrite(&data,sizeof(dat),1,fp);

of course, not the values, the adresses of variables are written to the file.

and my shiny idea, peah!

in this way, I'm looking forward to get your ideas! It's possible to use a structure with pointer logic?

dimm_coder
April 28th, 2003, 08:49 AM
Use members by value not by pointer. There are no any advantages of using standart types by pointer here.

#pragma pack(push,1)
struct
{
int a;
float b;
float c;
} data;
#pragma pack(pop)

serbet
April 28th, 2003, 09:16 AM
I have not used #pragma directive before. I am looking for it on internet but can you tell me a little?

what is the advantage?

rsmemphis
April 28th, 2003, 09:35 AM
You did it bass ackwards, so to speak... :)

You need to make the struct have the full members, and then use pointers to the members in the struct to access the values.

typedef struct{
int a;
float b;
float c;
}dat;

Only I must do is to assign the adresses of the variables to these pointers at the beginning of the program like this:

time = &dat.a;
pitch = &dat.b;
roll = &dat.c;

Of course, you need to declare time as int *time;, and access it by using *time... (pointer dereferencing).

mwilliamson
April 28th, 2003, 04:33 PM
Just a note to add; you could define an operator& or operator void* and keep the pointers in your structure. However, it is a better idea to remove them since they are not really needed. If you had variable length data, this would be a consideration though.

Kheun
April 28th, 2003, 07:16 PM
Originally posted by serbet
I have not used #pragma directive before. I am looking for it on internet but can you tell me a little?

what is the advantage?

See here (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/pragm.asp) for details. :)

Kheun
April 28th, 2003, 07:43 PM
I think storing pointer into file is often fundamentally incorrect. When the pointer is written into the file, the data pointed is NOT written. If the program restarted and pointers' values retrieved, the values would be invalid since they were pointing to some invalid memory addresses.