Article View: comp.std.c
Article #4859Array vs. structure alignment
From: Wil Evers
Date: Tue, 05 Mar 1996 11:43
Date: Tue, 05 Mar 1996 11:43
60 lines
2514 bytes
2514 bytes
A few days ago, I was working with some legacy header files having lots of
typedefs like this:
typedef char NAME_TYPE [NAME_SIZE];
typedef char ADDRESS_TYPE [ADDRESS_SIZE];
typedef char CITY_TYPE [CITY_SIZE];
These typedefs are a nuisance, because they hide their array nature,
obscuring code where these types are passed between functions. I tried to
fix this by adding:
typedef struct { char data[NAME_SIZE]; } PROPER_NAME_TYPE;
typedef struct { char data[ADDRESS_SIZE]; } PROPER_ADDRESS_TYPE;
typedef struct { char data[CITY_SIZE]; } PROPER_CITY_TYPE;
So I could write new code in terms of the PROPER_* types. This bit me when
I tried to add a proper type for a composite structure. The old code has:
typedef struct {
NAME_TYPE name;
ADDRESS_TYPE address;
CITY_TYPE city;
} CUSTOMER_TYPE;
so I added:
typedef struct {
PROPER_NAME_TYPE name;
PROPER_ADDRESS_TYPE address;
PROPER_CITY_TYPE city;
} PROPER_CUSTOMER_TYPE;
To my surprise, on one of the platforms I tested this (NextStep running on
an m68k) the offsets of both the `address' and `city' fields in
CUSTOMER_TYPE and PROPER_CUSTOMER_TYPE were different. This means I cannot
safely cast a pointer to a CUSTOMER_TYPE to a pointer to a
PROPER_CUSTOMER_TYPE or vice-versa. Being able to do these casts is
critical to me, because I need to interface to some of the legacy code
from my new code.
Regarding this, I have two questions:
1. Is there any technical reason why the memory layouts of CUSTOMER_TYPE
and PROPER_CUSTOMER_TYPE would be different? It seems to me that wrapping
an array into a structure is something relevant at compile-time, not at
run time. IMHO the generated code for accessing the fields in a
CUSTOMER_TYPE could be exactly the same as the code for accessing the
fields in a PROPER_CUSTOMER_TYPE.
2. Assuming there is no technical reason for this difference, shouldn't
the C standard require that the layouts of these two types be the same?
[Please don't ask me for an exact phrasing - I'll happily leave that to
the experts.]
Any comments? Suggestions?
- Wil
Wil Evers, <wil@ittpub.nl>, ITT Publitec Research and Development BV,
Amsterdam, Holland
Technical Details
Message-ID:
<1996Mar5.114346.1790@ittpub>Path:
arc1-ca.pugleaf.net!surfnet.nl!sun4nl!ittpub!ittpub!nntpShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!surfnet.nl!sun4nl!ittpub!ittpub!nntp Newsgroups: comp.std.c Subject: Array vs. structure alignment Message-ID: <1996Mar5.114346.1790@ittpub> From: wil@ittpub.nl (Wil Evers) Date: 5 Mar 96 11:43:46 WET Distribution: world Nntp-Posting-Host: lintilla