473,796 Members | 2,867 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
85 2444
Ian Collins <ia******@hotma il.comwrites:
Ben Bacarisse wrote:
>Ian Collins <ia******@hotma il.comwrites:
>>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?

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 don't think any of the proposed sizeof tests work due to possible
padding at the end of the struct. I know this has been covered by
later messages, but it seems worth summarising.
>>Anyway, if offsetof(vector ,z) == sizeof(double)* 2, how can
offsetof(vect or,y) be anything other than sizeof(double)?

Agreed. I still prefer my address test, though.
Fair enough, but the simplified offsetof (or sizeof) test has the
(small) advantage of not requiring an instance of vector to test.
Good point. That gives the offsetof version the edge, I'd say.

--
Ben.
Jun 27 '08 #21
On 14 Jun 2008 at 22:34, Tomás Ó hÉilidhe wrote:
Vector const v = { 99, 56, 42 };

if (99 == (&v.x)[0] &&
56 == (&v.x)[1] &&
42 == (&v.x)[2]) return;
Holy crap, are you trying to follow the CBF anti-style rules?
(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!)
It's nothing to do with integer values. Just passing around a
floating-point value won't magically change its bits.

In

double a=42;
double b=42.422242;
double c=1./3;
assert(a == 42);
assert(b == 42.422242);
assert(c == 1./3);

all the asserts will succeed.

Problems only arise when you start doing calculations and get
incremental rounding errors, either from separate steps in the
calculation, or from single steps where the compiled code uses a
temporary, or from type conversions (e.g. float promoted to double).

Jun 27 '08 #22
On 15 Jun 2008 at 3:56, vi******@gmail. com wrote:
Thomas: Please change your name to ASCII.
Probably he cares more about making a nationalist point than making life
simpler for people using non-unicode aware terminals/newsreaders. It's
interesting that most Russian, Chinese and Japanese posters are able to
swallow their pride enough to Latinize their names.

Jun 27 '08 #23
Antoninus Twink <no****@nospam. invalidwrites:
On 15 Jun 2008 at 3:56, vi******@gmail. com wrote:
>Thomas: Please change your name to ASCII.

Probably he cares more about making a nationalist point than making life
simpler for people using non-unicode aware terminals/newsreaders. It's
interesting that most Russian, Chinese and Japanese posters are able to
swallow their pride enough to Latinize their names.
Well, that helps me get a clearer picture of how you see the world.

I think it is quite reasonable that people should be able to spell
their names correctly, but that argument will be lost on someone who
does not even dare let their name be know.

--
Ben.
Jun 27 '08 #24
Ben Bacarisse wrote:
Antoninus Twink <no****@nospam. invalidwrites:
>On 15 Jun 2008 at 3:56, vi******@gmail. com wrote:
>>Thomas: Please change your name to ASCII.

Probably he cares more about making a nationalist point than making
life simpler for people using non-unicode aware
terminals/newsreaders. It's interesting that most Russian, Chinese
and Japanese posters are able to swallow their pride enough to
Latinize their names.

Well, that helps me get a clearer picture of how you see the world.

I think it is quite reasonable that people should be able to spell
their names correctly, but that argument will be lost on someone who
does not even dare let their name be know.
Just curious: what makes you believe that Antonius Twink is not a real name?

There are quite a few 'regulars' here that obviously don't use real names,
Default User for example and quite a few where it's hard to tell whether
it's a nick, a first or a last name. To me Antonius Twink /apperas/ to be a
real name.

Bye, Jojo
Jun 27 '08 #25
Joachim Schmitz wrote:
Ben Bacarisse wrote:
>Antoninus Twink <no****@nospam. invalidwrites:
>>On 15 Jun 2008 at 3:56, vi******@gmail. com wrote:
Thomas: Please change your name to ASCII.

Probably he cares more about making a nationalist point than making
life simpler for people using non-unicode aware
terminals/newsreaders. It's interesting that most Russian, Chinese
and Japanese posters are able to swallow their pride enough to
Latinize their names.

Well, that helps me get a clearer picture of how you see the world.

I think it is quite reasonable that people should be able to spell
their names correctly, but that argument will be lost on someone who
does not even dare let their name be know.
Just curious: what makes you believe that Antonius Twink is not a real
name?

There are quite a few 'regulars' here that obviously don't use real
names, Default User for example and quite a few where it's hard to
tell whether it's a nick, a first or a last name. To me Antonius Twink
/apperas/ to be a real name.
I suppose it's the Twink part that leads people to think he is a pseudo.
Also Antoninus isn't IME a very common name either. Besides he used to
(still does?) troll clc for a long time. It's unlikely that he is
stupid enough to troll under his real name.

Jun 27 '08 #26
Ben Bacarisse <be********@bsb .me.ukwrites:
Antoninus Twink <no****@nospam. invalidwrites:
>On 15 Jun 2008 at 3:56, vi******@gmail. com wrote:
>>Thomas: Please change your name to ASCII.

Probably he cares more about making a nationalist point than making life
simpler for people using non-unicode aware terminals/newsreaders. It's
interesting that most Russian, Chinese and Japanese posters are able to
swallow their pride enough to Latinize their names.

Well, that helps me get a clearer picture of how you see the world.

I think it is quite reasonable that people should be able to spell
their names correctly, but that argument will be lost on someone who
does not even dare let their name be know.
You appear to have totally missed the point. If you re-read Twinks reply
then all the necessary points are therein.

Hint : Most usenet posting Germans convert the German characters to
"oe", "ae" and "ss" etc as appropriate.
Jun 27 '08 #27

"pereges" <Br*****@gmail. comwrote in message news:
30************* *************** **...legroups .com...

For something more robust you can try helper functions like get() and
set(), or work with pointers using getp():

#include <stdio.h>

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

double *getp(vector *p,int i){
if (i==0) return &(p->x);
if (i==1) return &(p->y);
return &(p->z);
}

double get(vector *p,int i){
if (i==0) return p->x;
if (i==1) return p->y;
return p->z;
}

void set(vector *p,int i,double a){
if (i==0) {p->x=a; return;}
if (i==1) {p->y=a; return;}
p->z=a;
}

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

for (i=0; i<3; ++i)
set(&v,i,(i+1)* 10);

for(i = 0; i < 3; i++)
printf("%f\n", get(&v,i));

return 0;
}

Where you are sure the struct is laid out like an array, the contents
of get/set/getp can be simplied to a single line (possibly inlined).
But your main code doesn't change.

--
Bartc
Jun 27 '08 #28
In article <sl************ *******@nospam. invalid>,
Antoninus Twink <no****@nospam. invalidwrote:
>Probably he cares more about making a nationalist point than making life
simpler for people using non-unicode aware terminals/newsreaders. It's
interesting that most Russian, Chinese and Japanese posters are able to
swallow their pride enough to Latinize their names.
His name is perfectly Latinised. It just isn't Anglicised. Unless
you take "Latin" to be what the ancient Romans used, in which case
your own name isn't Latinised.

-- 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 #29
In article <g3**********@o nline.de>,
Joachim Schmitz <jo**@schmitz-digital.dewrote :
>Antoninus Twink <no****@nospam. invalidwrites:
[...]
>Just curious: what makes you believe that Antonius Twink is not a real name?
The fact that you've misread it might be taken as a clue.

-- 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 #30

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

Similar topics

19
6877
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
2416
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
2789
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
3026
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
35801
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
3800
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
9673
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
10452
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10221
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
10169
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
9050
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...
0
6785
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
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
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.