473,406 Members | 2,710 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Memory layout question

Here's a program:
#include <stdio.h>
int main(int argc, char **argv)
{
double an_array[] = {0.0, 1.0, 2.0, 3.0, 4.0};
typedef struct a_struct {double v0, v1, v2,v3, v4;} a_type;
typedef a_type *a_type_ptr;
a_type_ptr s_ptr;
s_ptr = (a_type_ptr) an_array;
printf( "%8.5f %8.5f %8.5f %8.5f %8.5f\n",
s_ptr -> v0,
s_ptr -> v1,
s_ptr -> v2,
s_ptr -> v3,
s_ptr -> v4 );
}

Using a recent gcc, this prints out the elements of the array
correctly, i.e.

0.00000 1.00000 2.00000 3.00000 4.00000

For what versions (if any) of standard C is this kluge required to
work? (same alignment and offsets for array items and struct members of
the same type).

TIA
Al
Nov 13 '05 #1
5 6356
On Tue, 18 Nov 2003 18:34:36 -0800, ac*****@easystreet.com wrote in
comp.lang.c:
Here's a program:
#include <stdio.h>
int main(int argc, char **argv)
{
double an_array[] = {0.0, 1.0, 2.0, 3.0, 4.0};
typedef struct a_struct {double v0, v1, v2,v3, v4;} a_type;
typedef a_type *a_type_ptr;
a_type_ptr s_ptr;
s_ptr = (a_type_ptr) an_array;
printf( "%8.5f %8.5f %8.5f %8.5f %8.5f\n",
s_ptr -> v0,
s_ptr -> v1,
s_ptr -> v2,
s_ptr -> v3,
s_ptr -> v4 );
}

Using a recent gcc, this prints out the elements of the array
correctly, i.e.

0.00000 1.00000 2.00000 3.00000 4.00000

For what versions (if any) of standard C is this kluge required to
work? (same alignment and offsets for array items and struct members of
the same type).

TIA
Al


"required to work"? Absolutely none.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #2
ac*****@easystreet.com wrote:
# Here's a program:
#
#
# #include <stdio.h>
# int main(int argc, char **argv)
# {
# double an_array[] = {0.0, 1.0, 2.0, 3.0, 4.0};
# typedef struct a_struct {double v0, v1, v2,v3, v4;} a_type;
# typedef a_type *a_type_ptr;
# a_type_ptr s_ptr;
# s_ptr = (a_type_ptr) an_array;
# printf( "%8.5f %8.5f %8.5f %8.5f %8.5f\n",
# s_ptr -> v0,
# s_ptr -> v1,
# s_ptr -> v2,
# s_ptr -> v3,
# s_ptr -> v4 );
# }
#
# Using a recent gcc, this prints out the elements of the array
# correctly, i.e.
#
# 0.00000 1.00000 2.00000 3.00000 4.00000
#
# For what versions (if any) of standard C is this kluge required to
# work? (same alignment and offsets for array items and struct members of
# the same type).

Potentially, every single one. The only safe standard way is to pack and
unpack the struct element by element. If you don't want to do that, you
can restrict your concern to just those machines this works on (practically
all of them) and include a dynamic test in the code start up to verify
your assumption.

--
Derk Gwen http://derkgwen.250free.com/html/index.html
Who's leading this mob?
Nov 13 '05 #3
ac*****@easystreet.com wrote:
Here's a program:
#include <stdio.h>
int main(int argc, char **argv)
{
double an_array[] = {0.0, 1.0, 2.0, 3.0, 4.0};
typedef struct a_struct {double v0, v1, v2,v3, v4;} a_type;
typedef a_type *a_type_ptr;
a_type_ptr s_ptr;
s_ptr = (a_type_ptr) an_array;
printf( "%8.5f %8.5f %8.5f %8.5f %8.5f\n",
s_ptr -> v0,
s_ptr -> v1,
s_ptr -> v2,
s_ptr -> v3,
s_ptr -> v4 );
}

Using a recent gcc, this prints out the elements of the array
correctly, i.e.

0.00000 1.00000 2.00000 3.00000 4.00000

For what versions (if any) of standard C is this kluge required to
work? (same alignment and offsets for array items and struct members of
the same type).

TIA
Al


In summary, you are trying to access a structure:
struct MyStruct
{
double v0;
double v1;
/* ... */
double v4;
};
as an array.

There is what I call the Structure Size Rule for C and C++:
"The size of a structure _may_ not be equal to the sum of
the size of its members."
This rule comes about because a compiler is allowed to
add "padding" elements after each member or field of a
structure. The compiler may want to add the padding to
make the fields easier or more convenient for the processor
to access.

Let us say we have a processor that likes to retrieve
32 bit quantities, known as a fetch. Let us also say
that the processor has an 8-bit char, 16-bit short int
and a 32-bit int (unsigned have the same sizes). When
the processor needs to fetch any of these quantities,
it fetches 32 bits at a time and discards the rest.

Given the following structure:
struct Example
{
char a;
short int b;
int c;
};

The member 'a' is 8-bits wide. The processor wants to
fetch 32 bits. Without any padding the process will
fetch 8 bits of 'a', 16 more bits of 'b' and finally
8 bits of 'c'. It will discard the unused bits, which
in this case, is no problem.

The member 'b' is 16-bits wide, but not at the first
fetch. The processor must fetch from the location
of the first member, remove the extraneous bits
then shift the remaining 16 bits to the correct
position. If we added 24 bits (32 bits - 8 bits
of char) of padding between 'a' and 'b', then the
fetching of 'b' would have no extraneous bits and
no shifting to take place -- more efficient.

The process of adding padding space is called
"alignment". Alignment allows processors to fetch
data more efficiently. However, adding padding
changes the size and layout of a structure. One
cannot map the members of a structure to a real
world structure because of the Structure Size Rule.

Packed Structures
-----------------
Some compilers have #pragmas that allow "packing"
of structures. The term "packing" referes to the
elimination of padding after members. This is not
a standard C facility. Also, many compilers may
allow packed structures but have problems accessing
data from them correctly.

Converting to Structures
------------------------
The best process for handling real world data structures
is to treat them as a sequence of "bytes" and extract
and build the data yourself. This technique also allows
one to handle Endianism (the ordering of "bytes" for
multi-byte units). Once the structure is filled,
it can then be accessed without any worries. The
opposite should be followed when creating a sequence
of bytes from a structure.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 13 '05 #4
On Tue, 18 Nov 2003 18:34:36 -0800, ac*****@easystreet.com wrote:
Here's a program:
#include <stdio.h>
int main(int argc, char **argv)
{
double an_array[] = {0.0, 1.0, 2.0, 3.0, 4.0};
The elements of the array are guaranteed to be contiguous in memory
(no gap between the end of an_array[0] and the beginning of
an_array[1], etc).
typedef struct a_struct {double v0, v1, v2,v3, v4;} a_type;
There is no guarantee that the members of the structure will be
contiguous (there may be padding between v0 and v1, etc).
typedef a_type *a_type_ptr;
a_type_ptr s_ptr;
s_ptr = (a_type_ptr) an_array;
There is no guarantee that the alignment of an_array will satisfy the
alignment requirement of the structure.
printf( "%8.5f %8.5f %8.5f %8.5f %8.5f\n",
s_ptr -> v0,
s_ptr -> v1,
s_ptr -> v2,
s_ptr -> v3,
s_ptr -> v4 );
}

Using a recent gcc, this prints out the elements of the array
correctly, i.e.

0.00000 1.00000 2.00000 3.00000 4.00000
Pure luck (good or bad depending on your viewpoint).

For what versions (if any) of standard C is this kluge required to
work? (same alignment and offsets for array items and struct members of
the same type).


There are only two standards (C89 and C99). The comments above apply
to both. The answer to your question is none.
<<Remove the del for email>>
Nov 13 '05 #5
in comp.lang.c i read:
ac*****@easystreet.com wrote: # For what versions (if any) of standard C is this kluge required to
# work? (same alignment and offsets for array items and struct members of
# the same type).

Potentially, every single one.
also, potentially none.
The only safe standard way is to pack and unpack the struct element by
element. If you don't want to do that, you can restrict your concern to
just those machines this works on (practically all of them) and include a
dynamic test in the code start up to verify your assumption.


and depend on the results of undefined behavior? no thanks.

--
a signature
Nov 13 '05 #6

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

Similar topics

21
by: Rabbit63 | last post by:
Hi: I want to show a set of records in the database table on the clicnt browser. I have two ways to do this (writen in JScript): 1.The first way is: <% var sql = "select firstname from...
10
by: Steven T. Hatton | last post by:
I just read something interesting in one of the PDFs located here: http://www.cs.wustl.edu/~schmidt/C++/ Sorry, I don't recall which file it was, and I'm too lazy to dig it up again ;) It says...
15
by: puzzlecracker | last post by:
Got Confused on the interview with memory alligment questions... PLEASE HELP -- How much bytes of memory will structs below take on 32 bit machine? What about 64 bit machine? Why is it different?...
6
by: lovecreatesbeauty | last post by:
Hello experts, 1. Does C guarantee the data layout of the memory allocated by malloc function on the heap. I mean, for example, if I allocate a array of 100 elements of structure, can I always...
7
by: toton | last post by:
Hi, I have a STL vector of of characters and the character class has a Boost array of points. The things are vector<Characterchars; and class Character{ private: array<Point,Npoints; }; Now...
11
by: Henryk | last post by:
I have something like class Params { public: const static char nOne = 1; const static int nTwo = 2; const static char nThree = 3; }; This is just a wrapper for globally used parameters in...
9
by: Bruno Barberi Gnecco | last post by:
I'm using PHP to run a CLI application. It's a script run by cron that parses some HTML files (with DOM XML), and I ended up using PHP to integrate with the rest of the code that already runs the...
6
by: \Frank\ | last post by:
On the Internet there are many descriptions of the memory layout for a DIB. But none that I can find for a Bitmap. Is that because a Bitmap's layout depends on a related device. If that's...
4
by: somenath | last post by:
I have a question regarding the memory allocation of array. For example int array; Now according to my understanding 10 subsequent memory location will be allocated of size sizeof(int) *10...
3
by: Peskov Dmitry | last post by:
Hi, What is the memory layout of an object, and the derived object. For example : class A { private: int prv_data; protected: int pro_data;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...
0
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,...

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.