Find size of variable size structure? 
Author Message
 Find size of variable size structure?

I'm passing messages consisting of header information, which is always the
same, followed by variable length data. I built a structure to hold the
message, but I'm having trouble figuring out just how big that structure is
(allowing for padding, etc):

typedef struct {
        int message_length;
        :
        :   /* other header stuff */
        :
        char data[1];   /* this is variable length */

Quote:
} fred;

I want to find out how far into fred my data[] starts. I am leery of
using

        offset = sizeof( fred ) - sizeof( fred.data )

because I'm worried that the compiler may do some padding at the end of
fred (or some other compiler might; I'm trying to be generic because this
program is going to be ported to an operating-sytem-to-be-named-later)*.

The only other thing I've come up with is to subtract pointers to fred and
the data in an actual instantiated structure (don't hold me to this code!):

        fred *timmy;
        timmy = (fred *)calloc(sizeof(fred)+data_length,1);

        offset = (char *)&(timmy->data[0]) - (char *)timmy;

which offends me because this is something the compiler should be able to
figure out before the program runs.

Any ideas?

Marty

* the current environment is QNX 4.1, a real-time UNIXish (well, POSIX)
OS using Watcom C.



Sun, 17 Mar 1996 09:53:18 GMT  
 Find size of variable size structure?


Quote:

[...]

>typedef struct {
>    int message_length;
>    :
>    :   /* other header stuff */
>    :
>    char data[1];   /* this is variable length */
>} fred;

>I want to find out how far into fred my data[] starts. I am leery of

Many thanks to the people who correctly suggested the offsetof() macro.

        offset = offsetof( fred, data)

is exactly what I needed.

Marty



Sun, 17 Mar 1996 23:07:23 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. how to find the size of a private structure

2. Finding the Size of a Structure.

3. variable size structure

4. About local variables and variable size???

5. Setting window size and cursor size

6. Setting Frame Size with Window Size

7. bitmap size and windows font size

8. Setting Frame Size with Window Size

9. How to set control size to view size

10. Size of viewable area compared to dialog size

11. How to implement the text's size changed with the view size

12. How to do int func(int size,int matrix[][size])

 

 
Powered by phpBB® Forum Software