473,791 Members | 2,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

QUERY: field offset rules within structures


I work a lot with multidimensiona l arrays of dynamic size in C,
implementing them using a single-dimensional C array and the
appropriate multipliers and offsets to index into it appropriately. I
tend to iterate over subsets of these arrays by walking a pointer and
an offset per dimension across their dimensions. I've found that this
tends to result in more performance in a portable manner than doing
explicit indexing calculations and hoping that the compiler hoists
invariant expressions out of the loops.

For example, rather than doing something like:

{
for (i=ilo; i<ihi; i+=istr) {
for (j=jlo; j<jhil j+=jstr) {
... a[(i-ailo)*imult + (j-ajlo)*jmult] ...
}
}
}

I would tend to do:

{
double* aptr = ...;
const int abumpj = ...;
const int abumpi = ...;

for (i=ilo; i<ihi; i+=istr) {
for (j=jlo; j<jhil j+=jstr) {
... *aptr ...

aptr += abumpj;
}
aptr += abumpi;
}
}

My question is motivated by the following desire: If I have an array
of structures, I'd like to be able to walk around *a single field*
within the array in a similar manner. For example, given the
structure:

struct _mystruct {
short x;
double y;
char z;
}

I would like the ability to walk through the "y" fields of the array
using a pointer and offsets.

I've been able to achieve this using a char* pointer as follows:

{
char* xptr = ...; /* point to y field of the initial element */
const int xbumpj = ...; /* express in bytes rather than */
const int xbumpi = ...; /* sizeof(doubles) */

for (i=ilo; i<ihi; i+=istr) {
for (j=jlo; j<jhil j+=jstr) {
... *((double*)xptr ) ...

xptr += xbumpj;
}
xptr += xbumpi;
}
}

I'd really prefer to eliminate the reliance on char* pointers and
pointer casting, however. In particular, I'd like to make xptr a
double*.

My question is therefore the following: does C have any requirements
on structure layout that would ensure that walking from field to field
within an array of structures will be evenly divisible by sizeof()
that field's type?

If not, it seems like my hope is in vain because the additive offsets
will be in terms of sizeof(<field type>) rather than bytes (or I will
have to cast my pointer back to char* before adding a generic offset
to it).

If so, I'm off and running. However, it's hard for me to believe that
C would ensure such rules on padding, which is why I ask.

The only other approach I can think of is to walk a structure pointer
over my array's elements and then dereference the pointer to access
the field. I guess I've avoided this approach simply due to the fact
that it seems more expensive (due to the field offset calculation
involved).

Does anyone have any other suggstions for how I might write such code
without relying on char* pointers?

Thanks,
-Brad
Nov 13 '05
11 3478
la************@ eds.com writes:
alignment rules are designed such that the answer to the original
question (will the fields of successive records in an array be spaced
by a multiple of the field type?) happens to be "yes."


I sincerely doubt that that's true. It may well be true for the
particular types you're interested in, but not for all types. Consider:

struct {
int a;
struct { char b[200]; } c;
} d[10];

I'm pretty sure that c won't be aligned on a 200 byte boundary (which
would require each element of d to be 400 bytes long).


You're right, I had oversimplified the rule in my mind to deal with
the scalar field types I was most interested in (in particular, I
don't tend to use char fields much). Your point is a good one: if I
typedef char ch200[200] and replace the c declaration above with
ch200, then I can't walk a ch200 pointer from one c field to the next
without casting it to a pointer to a smaller type. Thanks for
pointing this out, it's a subtle point that I probably would've
glossed over otherwise.

-Brad
Nov 13 '05 #11
On 09 Jul 2003 13:32:48 -0700, Bradford Chamberlain
<br**@cs.washin gton.edu> wrote:

I work a lot with multidimensiona l arrays of dynamic size in C,
implementing them using a single-dimensional C array and the
appropriate multipliers and offsets to index into it appropriately. I
tend to iterate over subsets of these arrays by walking a pointer and
an offset per dimension across their dimensions. I've found that this
tends to result in more performance in a portable manner than doing
explicit indexing calculations and hoping that the compiler hoists
invariant expressions out of the loops.

For example, rather than doing something like:

{
for (i=ilo; i<ihi; i+=istr) {
for (j=jlo; j<jhil j+=jstr) {
... a[(i-ailo)*imult + (j-ajlo)*jmult] ...
}
}
}

I would tend to do:

{
double* aptr = ...;
const int abumpj = ...;
const int abumpi = ...;

for (i=ilo; i<ihi; i+=istr) {
for (j=jlo; j<jhil j+=jstr) {
... *aptr ...

aptr += abumpj;
}
aptr += abumpi;
}
}

My question is motivated by the following desire: If I have an array
of structures, I'd like to be able to walk around *a single field*
within the array in a similar manner. For example, given the
structure:

struct _mystruct {
short x;
double y;
char z;
}

I would like the ability to walk through the "y" fields of the array
using a pointer and offsets.

I've been able to achieve this using a char* pointer as follows:

{
char* xptr = ...; /* point to y field of the initial element */
const int xbumpj = ...; /* express in bytes rather than */
const int xbumpi = ...; /* sizeof(doubles) */

for (i=ilo; i<ihi; i+=istr) {
for (j=jlo; j<jhil j+=jstr) {
... *((double*)xptr ) ...

xptr += xbumpj;
}
xptr += xbumpi;
}
}

I'd really prefer to eliminate the reliance on char* pointers and
pointer casting, however. In particular, I'd like to make xptr a
double*.

My question is therefore the following: does C have any requirements
on structure layout that would ensure that walking from field to field
within an array of structures will be evenly divisible by sizeof()
that field's type?

If not, it seems like my hope is in vain because the additive offsets
will be in terms of sizeof(<field type>) rather than bytes (or I will
have to cast my pointer back to char* before adding a generic offset
to it).

If so, I'm off and running. However, it's hard for me to believe that
C would ensure such rules on padding, which is why I ask.

The only other approach I can think of is to walk a structure pointer
over my array's elements and then dereference the pointer to access
the field. I guess I've avoided this approach simply due to the fact
that it seems more expensive (due to the field offset calculation
involved).

Does anyone have any other suggstions for how I might write such code
without relying on char* pointers?

If you have a struct STRUCT that contains a member (either scalar or
aggregate) of type TYPE and if the alignment for TYPE is the same as
its size (e.g., a double is of size 8 and must be aligned on an 8-byte
boundary), then sizeof(struct STRUCT) is guaranteed to be a multiple
of sizeof(TYPE). Consider

struct STRUCT{
...
TYPE member; /* TYPE could be double to match you example */
...
}
struct STRUCT mystruct[2];
intptr_t is0, is1, im0, im1;
is0 = (intptr_t)&myst ruct[0];
is1 = (intptr_t)&myst ruct[1];
im0 = (intptr_t)&myst ruct[0].member;
im1 = (intptr_t)&myst ruct[1].member;

is1-is0 is the number of characters between the start of
successive elements of the array which is, by definition,
sizeof(struct STRUCT).
im0-is0 is the number of characters from the start of the struct
to the start of member which is, by definition, offsetof(...).
im1-is1 is the same.
im0 == is0 + offsetof(...).
im1 == is1 + offsetof(...).
im1-im0 == is1 + offsetof(...) - is0 - offsetof(...)
== is1-is0
== sizeof(struct STRUCT)
im0 is a multiple of sizeof(TYPE) and can be represented as
k0*sizeof(TYPE) for some integer k0.
Similarly, im1 can be represented as k1*sizeof(TYPE) .
im1-im0 == (k1-k0)*sizeof(TYPE ) == sizeof(struct STRUCT).
(k1-k0) == sizeof(struct STRUCT)/sizeof(TYPE) which is the ratio
of two constants and therefore constant.

Consequently, if you want to step through a particular member for each
element of an array of struct, you can compute the quotient once as
part of program initialization and use it as the increment for your
pointer arithmetic, something like:

TYPE *ptr;
int dim, ratio;
...
ratio = sizeof(struct STRUCT) / sizeof(TYPE);
...
for (dim=0, ptr=&mystruct[0].member;
dim < max_dimension_o f_array;
dim++; ptr+=ratio){
...
}

This will not work if TYPE's alignment is different from its size.
For example, a double has size 8 but alignment 4. Then struct x{int
i1; double d1;} could easily have size 12 which is not a multiple of
8.

Unfortunately, I know of no portable way to test a type's alignment
requirement.
<<Remove the del for email>>
Nov 13 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
3068
by: Robert Brown | last post by:
suppose I have the following table: CREATE TABLE (int level, color varchar, length int, width int, height int) It has the following rows 1, "RED", 8, 10, 12 2, NULL, NULL, NULL, 20 3, NULL, 9, 82, 25
0
4201
by: Mike Knight | last post by:
(I've also posted this problem on microsoft.public.excel.programming) I have a MS Access 2003 Database named "AS400 Fields.mdb". This database contains links to tables on an AS400. In MS Excel 2003, I have VBA code that creates and executes queries using the Access database, and returns the results to an Excel sheet. The first time the query is executed, results are returned to Excel in usually less than 10 seconds. However, if the...
13
1754
by: Maxi | last post by:
I have a table (Table name : Lotto) with 23 fields (D_No, DrawDate, P1, P2,.....P21) and it has draw results from 1st Sep 2004 till date. I have another table (Table name : Check) with 15 fields (F1,F2,....F10, R6, R7, R8, R9, R10). I have few lacs combinations of 10 numbers in the Check table in the first 10 fields F1-F10). I want to check how many numbers from the first combination (record1 of Check table, fields F1-F10) matched in...
1
7800
by: Suffrinmick | last post by:
Hello Everyone I've built a database using Access 2000 which includes a query which is built using a form containing filters. No problem. When I export the results of the query to excel, (File > Export > Save as type: Microsft Excel 97-2000) one of the fields, which is a memo field type, loses any data over the first 255 characters. How do I get all the data into excel? Thanks
6
4850
by: jjturon | last post by:
Can anyone help me?? I am trying to pass a Select Query variable to a table using Dlookup and return the value to same select query but to another field. Ex. SalesManID SalesManName AT Alan Time
24
10369
by: funkyj | last post by:
PROBLEM STATEMENT: I want to calculate the byte offset of a field with a struct at compile time without instantiating an instance of the struct at runtime AND I want to do this in an ANSI standard compliant fashion. DISCUSSION: Below is a sample program that demonstrates my solution. My questions are:
3
4781
by: Hallvard B Furuseth | last post by:
I'm getting horribly lost in the strict aliasing rules. Is this code correct? struct A { int x; }; struct B { int x, y; }; int foo( struct A *a ) { struct B *b = (struct B *) a; return b->x - b->y; }
5
2519
by: Sam | last post by:
Hi, I have one table like : MyTable {field1, field2, startdate, enddate} I want to have the count of field1 between startdate and enddate, and the count of field2 where field2 = 1 between startdate and enddate, all in the same query.
6
4407
by: jsacrey | last post by:
Hey everybody, got a secnario for ya that I need a bit of help with. Access 97 using linked tables from an SQL Server 2000 machine. I've created a simple query using two tables joined by one field between them. The join field in both tables are indexed and I'm selecting 1 field from each table to lookup. The Access query is taking more than 60 second to retrieve 1 record and if I execute the same query within the Query Analyzer, it...
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9993
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5430
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5558
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.