tobold.org

correct • elegant • free

△ Comp.lang.c △

◅ Reading Date Stamp

Structure problem ▻

Structure problem

In article <87c8dc$fjr$1@nnrp1.deja.com>, <mikesta@my-deja.com> was
attempting to do binary I/O on structures.

First, you should read the FAQ, particularly questions 2.11, 2.12, 2.13,
and 20.5.

>        n = read (fd, &sec, 14);

It's always bad style to have a "magic number" (in this case 14) in
your code.  In this case, it's also wrong.  If you must do this, you
simply have to use `sizeof sec' here.  The compiler knows how big your
structure is, you don't.

>                   However the element sec.sseqno is
>incorrect when printed and the sizeof (sec) = 20 instead
>of what should be 14.

As I say, the compiler knows how big your structure is.  Why is it
20 in this case?  You have 9 chars, followed by a long, followed by
another char.  The first 9 chars consume 1 byte each, of course.  Next,
the compiler is probably leaving a gap of 3 bytes, so that the long is
suitably aligned.  Then there is another byte for the next char, then
(again, probably) a gap of 3 bytes padding.

If you made the long the first element of the structure, you would
probably reduce the size to 16 bytes.

Tim.
--
Tim Goodwin   | "If you don't know what closures are, you probably don't
Leicester, UK | want to know what closures are." -- Larry Wall

Original headers:

From: tjg@star.le.ac.uk (Tim Goodwin)
Newsgroups: comp.lang.c
Subject: Re: Structure problem
Date: 3 Feb 2000 17:00:22 -0000
Message-ID: <87cc7s$6ns$1@ltpcg.star.le.ac.uk>
References: <87c8dc$fjr$1@nnrp1.deja.com>

△ Comp.lang.c △

◅ Reading Date Stamp

Structure problem ▻