|
-
April 28th, 2003, 08:26 AM
#1
about pointers & structure
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?
-
April 28th, 2003, 08:49 AM
#2
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)
"UNIX is simple; it just takes a genius to understand its simplicity!"
-
April 28th, 2003, 09:16 AM
#3
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?
-
April 28th, 2003, 09:35 AM
#4
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).
-
April 28th, 2003, 04:33 PM
#5
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.
-
April 28th, 2003, 07:16 PM
#6
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 for details.
-
April 28th, 2003, 07:43 PM
#7
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|