www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2003/01/16/16:19:46

X-Originating-IP: [200.34.143.17]
From: "J. L." <jlsgarrido AT hotmail DOT com>
To: <djgpp AT delorie DOT com>
References: <b07318$3eg$1 AT news DOT online DOT de>
Subject: Re: sizeof(struct x) doesn't compile -- how to do it ?
Date: Thu, 16 Jan 2003 15:18:57 -0600
MIME-Version: 1.0
X-Priority: 3
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook Express 5.50.4807.1700
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4807.1700
Message-ID: <OE172uNUICAazonR8uH0000625c@hotmail.com>
X-OriginalArrivalTime: 16 Jan 2003 21:19:30.0161 (UTC) FILETIME=[F4F26E10:01C2BDA4]
Reply-To: djgpp AT delorie DOT com

"Lars Hansen" <lars DOT o DOT hansen AT gmx DOT de> wrote:


> #include "stdlib.h"
>
> struct x
>  {
>   double x;
>  };
>
> int main()
>  {
>   x* n=malloc(2*sizeof(struct x));


Huh? Maybe you are thinking in something like

struct x
{
  double y;
};

int main()
{
  struct x *n = malloc(2*sizeof(struct x));
/* better is the C idiom
struct x *n = malloc(2*sizeof *n);
*/
}

[snip]

> And also: if i have an array of a struct with several elements how can i
know
> at which byte an element of the nth struct is in that array with djgpp (eg
> after writing a struct array to file and then loading this data without
> knowing how to "synchronize" djgpps compiler struct array generation and
> saving and an other compilers array struct generation and loading means
one
> best knows the byte position (and length))
>

ISO C defines the macro offsetof that gives the byte offset of a field
whitin a struct. And if the index in array is k, then

k*sizeof *n +offsetof(y) */or k*sizeof(struct x) + offsetof(y) */

gives the answer in you example.

But you must be careful; binary data isn't portable between compilers.

HTH

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019