473,785 Members | 2,794 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How come C allow structure members to be addressed like an array ?

#include <stdio.h>

typedef struct
{
double x, y, z;
}vector;

int main(void)
{
int i;
vector v;
double *cord;

v.x = 10;
v.y = 1;
v.z = 2;

cord = &v.x;

for(i = 0; i < 3; i++)
{
printf("%f\n", cord[i]);
}
return 0;
}

here's the output i get:
10.000000
1.000000
2.000000

which is the same as v

i don't how it happens as i was just trying some random ideas but
great stuff really. helped me to reduce some of my code to almost
1/3rd its size.
Jun 27 '08 #1
85 2441
On Jun 14, 5:37*pm, pereges <Brol...@gmail. comwrote:
#include <stdio.h>

typedef struct
{
* double x, y, z;

}vector;

int main(void)
{
* int i;
* vector v;
* double *cord;

* v.x = 10;
* v.y = 1;
* v.z = 2;

*cord = &v.x;

*for(i = 0; i < 3; i++)
*{
* printf("%f\n", cord[i]);
*}
return 0;

}

here's the output i get:
10.000000
1.000000
2.000000

which is the same as v

i don't how it happens as i was just trying some random ideas but
great stuff really. helped me to reduce some of my code to almost
1/3rd its size.
This is not portable but at the low level there is no difference
between a structure containing three doubles and an array of three
doubles in this case.

You cannot assume this, as some implementation might introduce pads
for byte alignment in structures.

The following articles should help:

http://www.eventhelix.com/RealTimeMa...ranslation.htm
http://www.eventhelix.com/RealTimeMa...anslation2.htm
http://www.eventhelix.com/RealTimeMa...anslation3.htm

--
EventStudio 4.0 - http://www.Eventhelix.com/Eventstudio/
Sequence diagram based systems engineering tool
Jun 27 '08 #2
In article <a0************ *************** *******@34g2000 hsf.googlegroup s.com>,
EventHelix.com <ev********@gma il.comwrote:
>This is not portable but at the low level there is no difference
between a structure containing three doubles and an array of three
doubles in this case.
Fields in a struct are aligned in "an implementation-defined manner
appropriate to [their] type". The clear implication is that the
padding is a property of the type (rather than each individual
instance) and so it would be unreasonable for the padding of
successive members of the same type in a struct to be different from
that in an array - which is to say, there should be no padding between
fields of the same type.

Can anyone come up with a reason (other than perverseness) why an
implementation would not do this?

-- Richard
--
In the selection of the two characters immediately succeeding the numeral 9,
consideration shall be given to their replacement by the graphics 10 and 11 to
facilitate the adoption of the code in the sterling monetary area. (X3.4-1963)
Jun 27 '08 #3
one can solve this problem using a vector iterator function like below
but i am not sure if the solution is generic :

#include <stdio.h>

typedef struct
{
double x, y, z;

}vector;

double vector_iterator (vector *a, int i)
{
double ret;
if(i == 0)
ret = a->x;
if(i == 1)
ret = a->y;
if(i == 2)
ret = a->z;
return ret;
}

int main(void)
{
int i;
vector v;
double coord;

v.x = 10;
v.y = 1;
v.z = 2;

for(i = 0; i < 3; i++)
{
coord = vector_iterator (&v, i);
printf("%f\n", coord);
}
return 0;

}

Jun 27 '08 #4

Others have explained the padding situation, but if you want re-
assurance, you might add a routine to the start of your code that
makes sure it's OK:

void EnsureItWorks(v oid)
{
Vector const v = { 99, 56, 42 };

if (99 == (&v.x)[0] &&
56 == (&v.x)[1] &&
42 == (&v.x)[2]) return;

puts("ERROR: There's padding in the Vector struct.");

exit(EXIT_FAILU RE);
}

int main(void) { EnsureItWorks() ; }
(I know that floating-point arithmetic isn't exact but as far as I
know it's exact for integer values... but I'm open to correction!)
Jun 27 '08 #5
Tomás Ó hÉilidhe wrote:
void EnsureItWorks(v oid)
{
Vector const v = { 99, 56, 42 };

if (99 == (&v.x)[0] &&
56 == (&v.x)[1] &&
42 == (&v.x)[2]) return;
*BANG*
(&v.x)[1] or (&v.x)[2] is a trap representation :)
puts("ERROR: There's padding in the Vector struct.");

exit(EXIT_FAILU RE);
}
Jun 27 '08 #6
Tomás Ó hÉilidhe wrote:
Others have explained the padding situation, but if you want re-
assurance, you might add a routine to the start of your code that
makes sure it's OK:

void EnsureItWorks(v oid)
{
Vector const v = { 99, 56, 42 };

if (99 == (&v.x)[0] &&
56 == (&v.x)[1] &&
42 == (&v.x)[2]) return;

puts("ERROR: There's padding in the Vector struct.");

exit(EXIT_FAILU RE);
}

int main(void) { EnsureItWorks() ; }
A very verbose way of writing

int main()
{
assert( sizeof(vector)= =sizeof(double) *3);
}

--
Ian Collins.
Jun 27 '08 #7
Hi

On Sun, 15 Jun 2008 10:51:28 +1200, Ian Collins wrote:
Tomás Ó hÉilidhe wrote:
> if (99 == (&v.x)[0] &&
56 == (&v.x)[1] &&
42 == (&v.x)[2]) return;
puts("ERROR: There's padding in the Vector struct.");
exit(EXIT_FAILU RE);
A very verbose way of writing
assert( sizeof(vector)= =sizeof(double) *3);
The two are not equivalent and neither is perfect. Better is:

assert( offsetof(vector ,y) == sizeof(double)
&& offsetof(vector ,z) == sizeof(double)* 2 );

viza
Jun 27 '08 #8
viza wrote:
Hi

On Sun, 15 Jun 2008 10:51:28 +1200, Ian Collins wrote:
>Tomás Ó hÉilidhe wrote:
>> if (99 == (&v.x)[0] &&
56 == (&v.x)[1] &&
42 == (&v.x)[2]) return;
puts("ERROR: There's padding in the Vector struct.");
exit(EXIT_FAILU RE);
>A very verbose way of writing
assert( sizeof(vector)= =sizeof(double) *3);

The two are not equivalent and neither is perfect. Better is:

assert( offsetof(vector ,y) == sizeof(double)
&& offsetof(vector ,z) == sizeof(double)* 2 );
Why?

Anyway, if offsetof(vector ,z) == sizeof(double)* 2, how can
offsetof(vector ,y) be anything other than sizeof(double)?

--
Ian Collins.
Jun 27 '08 #9
Keith Thompson wrote:
Ian Collins <ia******@hotma il.comwrites:
>Keith Thompson wrote:
>>Ian Collins <ia******@hotma il.comwrites:
Ben Bacarisse wrote:
Tomás's code is over complex (one test is enough) and could fail in
unusual cases (see my other posting) and your test will be thrown if
there is padding at the end of the struct.
>
OK, make it

assert( sizeof(vector[2])==sizeof(doubl e)*6 );

Or even a compile time assert:

const int n = 1/( sizeof(vector[2])==sizeof(doubl e)*6 );
I think that this:

sizeof(vector) == sizeof(double) * 3

would suffice. An array of two thingies must have twice the size of a
single thingie, for any applicable value of "thingie".
It would, my last suggestion was pointless. It would still fail if
there were padding at the end of the struct. I would still use the one
above, the chances of padding at the end but not in the middle are slim.

I'd say the chances of padding at the end are higher than the chances
of padding in the middle.

Consider
struct foo { char a; char b; char c; };

It's plausible that sizeof(struct foo) == 4, with a padding byte at
the end.

This is less likely to happen for a struct containing doubles, though.
That why I suggested the compile time assert, it's unlikely, but worth
picking up as soon as possible.

--
Ian Collins.
Jun 27 '08 #10

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

Similar topics

19
6876
by: Thomas Matthews | last post by:
Hi, Given a structure of pointers: struct Example_Struct { unsigned char * ptr_buffer; unsigned int * ptr_numbers; }; And a function that will accept the structure:
4
2825
by: Thomas Matthews | last post by:
Hi, I'm writing code for an embedded system. In the system a Timer has 4 memory mapped registers of 32-bit lengths in contiguous locations: Timer 0: 0x1000 Configuration register 0x1004 Control register 0x1008 Input register 0x100C Output register.
6
4206
by: Eric Smith | last post by:
Is a structure containing an incomplete array as its last element (per paragraph 2 of section 6.7.2.1 of ISO/IEC 9899:1999 (E)) itself an incomplete type? That appears to be indicated by paragraph 22 of section 6.2.5. If so, that seems to make it difficult to allocate such structures, because sizeof() is not allowed on incomplete types (paragraph 1 of section 6.5.3.4). For instance, I've routinely done things like this: struct foo {...
11
2415
by: Mannequin* | last post by:
Hi all, I'm working on a quick program to bring the Bible into memory from a text file. Anyway, I have three questions to ask. First, is my implementation of malloc () correct in the program to follow? Second, have I correctly passed the structure's pointer to the functions in this program?
15
2781
by: damian birchler | last post by:
Hi I'm wondering of what type a structure is. Of course, it is a _structure_, but an array isn't an _array_ either. So of what type is a structure? I'd say a pointer, am I right?
10
2134
by: nambissan.nisha | last post by:
I am facing this problem.... I have to define a structure at runtime as the user specifies... The user will tell the number of fields,the actual fields...(maybe basic or array types or multiple arrays,etc) I do not understand how to define the structure at run time.i.e.what fields it will contain.
6
3024
by: noone | last post by:
What is the syntax to access members of a structure without explicitly naming the structure in every access? struct mytype { int a; char* b; long c; } IT; How can I access the structure members in a way similar to the old pascal
5
35796
Banfa
by: Banfa | last post by:
I thought I would write a little article about this because it is regularly asked as a question in the Forums. Firstly this is a C++ issue, it is strictly against the rules of C to create a class with no members. This makes sense because the only real use for a structure or class with no data members and virtual functions is as the base from which to derive other classes and structures or as a container for non-virtual methods. The reason...
5
3797
by: =?Utf-8?B?QXlrdXQgRXJnaW4=?= | last post by:
Hi Willy, Thank you very much for your work. C++ code doesnot make any serialization. So at runtime C# code gives an serialization error at "msg_file_s sa = (msg_file_s) bf.Deserialize(ms);" I thought that it is very hard to memory map structure array. I need both read and write memory mapped file at both side of C# and C++.
0
9645
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
10152
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...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
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
6740
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
5381
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.