f



Casting the first member of a struct (and back)

Hi, Gurus,

i'm trying to clarify my understanding of how exactly the casting rules wor=
k for the first member of a C struct. For example...

struct Base {
  int foo;
  ...
};

struct Subclass {
  Base base;
  ...
};

(struct typedefs elided)

Subclass sub =3D { {...}, ... };
Base * b =3D (Base*)⊂

It is my understanding (please correct me if i'm wrong) that that is comple=
tely kosher in C because C guarantees (IIUC) that the offset of the first m=
ember in the struct is 0.

What i'm not clear on is if the reverse of that cast is legal:

Subclass * original =3D (Subclass*)b;

(insofar as the coder knows that the conversion is legal, of course, e.g. b=
y checking a type-id indicator stored in the base type.)

My intuition says, "if the offset is 0, the reverse cast must be just as le=
gal because the address is the same," but i am experienced enough to know t=
hat intuition is only a part of the story when it comes to details like thi=
s :/. Additionally, i seem to remember reading that C++ does _not_ guaranty=
 that the addresses are the same for such casts.

Can one of you provide me a bit of enlightenment on this topic?

:-?
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
stephan
8/7/2013 6:06:20 AM
comp.lang.c.moderated 1019 articles. 0 followers. Post Follow

4 Replies
271 Views

Similar Articles

[PageSpeed] 26

On 07/08/2013 07:06, stephan beal wrote:
> Hi, Gurus,
>
> i'm trying to clarify my understanding of how exactly the casting rules work for the first member of a C struct. For example...
>
> struct Base {
>    int foo;
>    ...
> };
>
> struct Subclass {
>    Base base;
>    ...
> };
>
> (struct typedefs elided)
>
> Subclass sub = { {...}, ... };
> Base * b = (Base*)⊂

In plain terms, take the memory of sub and treat it as a base. Looks 
fine to me because of the prohibition of initial padding in any object.
>
> It is my understanding (please correct me if i'm wrong) that that is
> completely kosher in C because C guarantees (IIUC) that the offset of
> the first member in the struct is 0.
>
> What i'm not clear on is if the reverse of that cast is legal:
>
> Subclass * original = (Subclass*)b;

Whiist this should work in the current context, it is dangerous as it 
relies on the memory addresses by a b* actually containing a subclass 
object. Hence I would expect that to be generally classed as undefined 
behaviour.

>
> (insofar as the coder knows that the conversion is legal, of course,
> e.g. by checking a type-id indicator stored in the base type.)

You are confusing 'legal' with 'will work as expected'. The 
implementation takes the programmer's word that a cast is valid. That is 
the nature of casts in C. They are effectively an unchecked way of 
changing the type of an area of memory.
>
> My intuition says, "if the offset is 0, the reverse cast must be just as legal because the address is the same,"
> but i am experienced enough to know that intuition is only a part of the story when it comes
? to details like this :/. Additionally, i seem to remember reading that 
C++ does _not_ guaranty
> that the addresses are the same for such casts.
Well C++ makes the same guarantees as C for Plain Old Data types (i.e 
structs that conform to the requirements of C) However, the general 
rules in C++ have to accommodate inheritance (possibly multiple). As a 
result C++ programmers avoid C-style casts because they are blunt tools 
in the context of C++.

I guess one of the resident C specialists will quote you chapter and verse.

Francis
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Francis
8/7/2013 6:51:08 PM
On 08/07/2013 02:06 AM, stephan beal wrote:
> Hi, Gurus,
> 
> i'm trying to clarify my understanding of how exactly the casting
> rules work for the first member of a C struct. For example...
> 
> struct Base {
> int foo;
> ...
> };
> 
> struct Subclass {
> Base base;
> ...
> };
> 
> (struct typedefs elided)
> 
> Subclass sub = { {...}, ... };
> Base * b = (Base*)⊂
> 
> It is my understanding (please correct me if i'm wrong) that that is
> completely kosher in C because C guarantees (IIUC) that the offset of
> the first member in the struct is 0.
> 
> What i'm not clear on is if the reverse of that cast is legal:
> 
> Subclass * original = (Subclass*)b;
> 
> (insofar as the coder knows that the conversion is legal, of course,
> e.g. by checking a type-id indicator stored in the base type.)
> 
> My intuition says, "if the offset is 0, the reverse cast must be just
> as legal because the address is the same," but i am experienced
> enough to know that intuition is only a part of the story when it
> comes to details like this :/. Additionally, i seem to remember
> reading that C++ does _not_ guaranty that the addresses are the same
> for such casts.

"A pointer to a structure object, suitably converted, points to its
initial member (or if that member is a bit-field, then to the unit in
which it resides), and vice versa." (6.7.2.1p15)

The "and vice versa" covers the case that you're asking about.

-- 
James Kuyper
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
James
8/7/2013 6:51:11 PM
On 2013-08-07, stephan beal <sgbeal@googlemail.com> wrote:

> My intuition says, "if the offset is 0, the reverse cast must be
> just as legal because the address is the same," but i am experienced
> enough to know that intuition is only a part of the story when it
> comes to details like this :/. Additionally, i seem to remember
> reading that C++ does _not_ guaranty that the addresses are the same
> for such casts.       

it's syntactically correct, but may fail, especially on bad input.

-- 
⚂⚃ 100% natural

--- news://freenews.netfront.net/ - complaints: news@netfront.net ---
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Jasen
8/7/2013 6:51:46 PM
Francis Glassborow <francis.glassborow@btinternet.com> writes:
[...]
> You are confusing 'legal' with 'will work as expected'. The 
> implementation takes the programmer's word that a cast is valid. That is 
> the nature of casts in C. They are effectively an unchecked way of 
> changing the type of an area of memory.

Well, pointer casts are.  Numeric casts just convert a value of one type
to another in a (usually) well-defined way.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Keith
9/2/2013 9:07:15 AM
Reply:

Similar Artilces:

Can *common* struct-members of 2 different struct-types, that are the same for the first common members, be accessed via pointer cast to either struct-type?
Assume identical common top struct members: struct a { int i1; char c1; short sa1[3]; }; struct b { int i2; char c2; short sa2[3]; int differ_here; }; struct a tmp; Are the following 2 line always equivalent (as in: yielding the same lvalue) and allowed: tmp.c1 ((struct b*)&tmp)->c1 Thanks. - John. In article <37f36566-0b91-4ee4-9135-6890c7c8de7a@12g2000vba.googlegroups.com>, John Reye <jononanon@googlemail.com> wrote: > Are the following 2 line always equivalent (as in: yielding the same > lvalue) and allowed: Maybe not. The guarantee only ...

C struct member default values in struct
Is there a version of C or C++ extension which takes this: struct SAbc { int a; int b; int c; }; struct SAbc myAbcVar[] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; And lets me change my structure to this: struct SAbc { int a; int b; int c; int d; }; Without having to do this manually: struct SAbc myAbcVar[] = { { 1, 2, 3, -1 }, { 4, 5, 6, -1 }, { 7, 8, 9, -1 } }; By allowing me instead to do something ...

Converting from C style struct offset to C++ style member pointer
When I get a struct offset from a C style API as int. I.e.: struct S { int I1; double D1; int I2; }; int offset = offsetof(S, I2); Now in C++ code I would like to convert this offset to a type safe C++ member pointer of type int S::*. Older gcc versions simply accepted a cast, newer version reject the cast. Marcel Hi Marcel % Marcel M�ller wrote: > When I get a struct offset from a C style API as int. I.e.: > > struct S > { int I1; > double D1; > int I2; > }; > > int offset = offsetof(S, I2); > > Now in C++ co...

Convert C/C++ struct to matlab struct
Hi all I have two applications the first is written in c language and the other in matlab language, they are both communicateby using tcp. Application 1(c language) send struct data to application 2(matlab language). How can i make matlab recognize the received data as a struct data? For example : C code myfile.h struct My_struct1 { int x; int y[10]; }; struct My_struct2 { char x1; char y1[10]; float x2; float y2[10]; double x3; double y3[10]; My_struct1 z; }; I am sending My_struct2 from c to matlab. This i...

pointer to a member of a struct which is in turn a member of an array of structs
Hi folks -- I have a 4-long array t[ ] of of struct Targets. And a table of int * in p[ ]. I need to set up the int * entries in p[ ] such that each can reference an int in any member of the Targets t[ ] array. How to do it? Much-simplified example: 1. #include <stdio.h> 2. int main(int argc, char* argv[ ]) { 3. int ix; 4. typedef struct { int num1; int num2; int num3; } Targets; 5. Targets t[4]; 6. 7. typedef struct { int *number; } Pointers; 8. Pointers *ap; 9. Pointers p[3] = { { &t[?].num1 }, 10. ...

Struct in C and C++
Struct in C and C++ are same? Can Struct in C handle member functions? >>>> Struct in C and C++ are same? Can Struct in C handle member functions? No vishnupriya.sureshbabu@gmail.com wrote: > Struct in C and C++ are same? NO Can Struct in C handle member functions? NO Jaspreet wrote: > vishnupriya.sureshbabu@gmail.com wrote: > > Struct in C and C++ are same? > NO > > Can Struct in C handle member functions? > > NO struct X { void (*f)(); }; .... void ConstructX(struct X * x) { x = &someFun; } It's just a lot more hand work. ...

C or C++ first?
Should I learn C first? Or can I go straight to C++ or C#? Thanks in advance. [Crossposts removed. If you read this newsgroup, you will see this answer. If you don't, you won't.] English Teacher wrote: > Should I learn C first? Or can I go straight to C++ or C#? Learn C. It is not necessary to learn either C++ or C#, but you may if you wish. Nevertheless, you should learn C before learning either of those. -- Richard Heathfield : binary@eton.powernet.co.uk "Usenet is a strange place." - Dennis M Ritchie, 29 July 1999. C FAQ: http://www.eskimo.com/~scs/C-faq/top.ht...

C
I have 3 different structures with each structure having the same first member (int type). I would like every structure of type 1 to have a 1 in the type field, every structure of type 2 to have 2 in the type field etc. I want instances of each structure to have the type value properly initialized, and I also want that member to be const. Basically, I want 1 member of a structure to be initialized to a value and be unchangeable. Is there a way to do this in C? Mas wrote: > I have 3 different structures with each structure having the same first > member (int type). I would like every ...

Why does C have both . and -> for addressing struct members?
Hi. Why does C have both . and -> for addressing struct members? Is it possible to have such modified language syntax, where we can take p as a pointer to struct and get a struct member's value just as p.value? On 12/5/2012 11:00 PM, Dennis Yurichev wrote: > Hi. > > Why does C have both . and -> for addressing struct members? > > Is it possible to have such modified language syntax, where we can take > p as a pointer to struct and get a struct member's value just as p.value? > probably mostly for historical reasons?... like, early on, th...

C struct compatibility when they have the same initial members
The basic query is: If two or more struct types begin with the same types of members is it possible to treat a struct which has just the common part as compatible with the others without the use of casts? Specifics below. Before someone tells me just to cast the pointers ... I know/think that can be done but was wondering if there is a more robust way that avoids them by simply making the types sufficiently compatible that casts become unnecessary. This is for a fairly standard problem. I have a number of node types that begin with next and prev pointers so that the nodes a...

type casting of a ptr to a c struct
I have a c struct from old code that cannot be modified and I am trying to write a wrapper C++ class around it. This class is often passed as a pointer to some c functions of a library and I wanted to keep my new class transparent and compatible with those functions. That is, when using the code, I should be able to do either: oldVector xyz; function( &xyz ); myVector xyz; function( &xyz ); My original implementation solved the issue using inheritance. That is, in pseudo code: // old code typedef struct {float x, y, z;} oldVector; /// my class class myVector : public o...

Pointer to pointer to struct/first member
I know that a pointer to a structure and a pointer to its first member are largely interchangeable. Is that true for pointers to pointers? I.e.: struct foo { int bar; }; void int_fn(int **baz) { /* do stuff */ } void foo_fn(struct foo *foo_ptr) { int_fn((int **)&foo_ptr); /* Is this cast defined? */ /* do other stuff with foo_ptr */ } I have a sneaking feeling that it isn't, even though it's likely to work on just about any mainstream implementation. I supposed that the "safe" version would be ...

Accessing C struct members via T_PTROBJ
I recently wrote a Perl extension in which h2xs pretty much handled all the XS details for me. I now need to go back and access C struct members from within Perl if possible. The typemap file indicates that my struct pointer (SHA *) got mapped as a T_PTROBJ. Is there any way I can use this info to do reads and writes on the various struct members? Or, do I need to go back and write accessor routines in C? TIA, Mark Mark Shelor wrote: > I recently wrote a Perl extension in which h2xs pretty much handled all > the XS details for me. I now need to go back and access C struct ...

Which to learn first: C or C++?
Which programming language should I learn first: C or C++? Thanks! -- --------------------------------- --- -- - Posted with NewsLeecher v3.7 Final Web @ http://www.newsleecher.com/?usenet ------------------- ----- ---- -- - dydx13@hotmail.com wrote: > Which programming language should I learn first: C or C++? nice trolling. dydx13@hotmail.com wrote: > Which programming language should I learn first: C or C++? Go read your other post in this newsgroup on the same subject. It has plenty of responses. Failing that, search the archives of this group since many other people have a...

C programming problem: how to cast a union to struct
Hi all, I've encounter a error of my program.. I've created a testing c file as follows: error C2440: 'type cast' : cannot convert from 'struct c ' to 'union a ' struct c{ char t[5]; }; typedef union a{ char st[5]; struct c cc; }au; struct b{ au abc; }; struct ba { int v; struct c y; }; typedef struct ba* BA; typedef struct b* B; typedef struct c* C; void main(void) { BA test2; B test; C n; test->abc=(au)test2->y; return; } does anyone know how to solve this problem?? help?? pikayo wrote: > > Hi all, > > I've...

initiaization if struct members in "c"
In unix/linux, the follwoing code passed gcc compilation: struct proto_ops_test { int family; struct module* owner; }; struct proto_ops inet_stream_ops = { .family = 1, .owner = NULL }; under windows , visual c , it gives an error test.c(138) : error C2065: 'family' : undeclared identifier is there a sloution (like a compiler flag, some workaround,etc) ? regards, sting No. This is an extension to the C language that only gcc provides. On other compilers, including Visual C++, you need to do: struct proto_ops inet_stream_ops = { 1, ...

Which to learn first C or C++?
Hello, I'm currently attending a university majoring in Computer Science. I took C and C++ at a community college and got an A in both classes. That was three years ago. I have not programmed or anything like that in three years. I want to get back into the programming scene so I have a question: Which should I relearn first, C or C++? I have forgotten a lot about both languages so please tell me which i should relearn first! Thanks! -- --------------------------------- --- -- - Posted with NewsLeecher v3.7 Final Web @ http://www.newsleecher.com/?usenet ------------------- ...

C style casting or c++
Hi All, ------------- #include <iostream> using namespace std; template<class A, class B, class C> inline A max(B const& num1, C const& num2) { return (A)num1>(A)num2?(A)num1:(A)num2; } How can i implement this template function more c++ style? Any improvement are welcome? phal [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] "phal" <betterdie@gmail.com> schrieb im Newsbeitrag news:1134714493.932934.186340@o13g2000cwo.googlegroups.com... > Hi All, > > ...

Coming back from C to C++
I started out with C++ about 8 years ago, but in the last two years or so I switched to doing a lot of C programming, so I've been out of the loop for a while. Anyway I've a few quick questions to ask: Currently what's the biggest integer type in C++? Does C++ have all the <stdint.h> types such as uint_fast64_t? I use these types a lot. Back when I did C++ programming a few years ago, I don't think all C++ implementations were guaranteed to have <stdint.h>. Have things changed? Also, does C++ have the "long long" integer type that's guaranteed to be...

C++ struct same as C++ class
Hi, C++ struct is same as C++ class except for the default access specifier. you can do everything with C++ struct that you can with C++ class. I know this. what I want to know is, Is this the specification of C++ standard. If yes, was it always the part of specification? and could this behaviour be compiler specific? ( I am trying to convince a bunch of programmers, and these answers would help.) -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] herhighness wrote: > Hi, > > C++ struct ...

How to implement C++ class heritage properties in C using C struct?
hi,all, I have a C++ program need to convert to c language to be used in a emabedded system. the problem is that the original code was writtern in C++ language with Parent class and some child class. How can I invert these C++ code into pure c code by using struct in C language? Can somebody give me any ideas? thanks. For example, how to conver the following code into pure c code? class PARENT { public: virtual int Init(); virtual int Add(); virtual int Sub(); int Otherfunc(); private: int x; int y; int z; }; class CHILD1: publi...

How to implement C++ class heritage properties in C using C struct?
hi,all, I have a C++ program need to convert to c language to be used in a emabedded system. the problem is that the original code was writtern in C++ language with Parent class and some child class. How can I invert these C++ code into pure c code by using struct in C language? Can somebody give me any ideas? thanks. For example, how to conver the following code into pure c code? class PARENT { public: virtual int Init(); virtual int Add(); virtual int Sub(); int Otherfunc(); private: int x; int y; int z; }; class CHILD1: public PARENT { public: int Init(); int Add(); int CH...

C++ member pointers and anonymous structs/unions broken?
Hi, The program below stores the 5 unsigned ints a, b, c, x and y in an anonymous union, so that they share storage space with state[]. Additionally x and y share storage space with nums[]. The main function displays the address of each of the 5 integers twice, first using the member pointer table "members" and then using an instance of myclass. The results are surprising: the values for x and y are incorrect when using the member pointers. laptop:~/scratch> g++ -W -Wall foo.cc -o foo laptop:~/scratch> ./foo a -> 0x8049718 0x8049718 b -> 0x804971c 0x804971c x -> 0x8...

struct's first member and the NULL pointer
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var[3] = {NULL}; My doubts are followed: 1) When I set the high warning level of the compiler (-Wall) that gives some warnings. What are those warnings? 2) Is there any difference in the above initialization if I declare the struct's first element as a value or a pointer? Does this have any impact on the usage of NULL pointer in the above context of initialization? #include <stdio.h> struct node { int a; char *b; }; int main...

Web resources about - Casting the first member of a struct (and back) - comp.lang.c.moderated

Casting (fishing) - Wikipedia, the free encyclopedia
Casting techniques vary with the type of fishing involved. Fly fishermen use artificial flies as a lure and use lighter rods and lines. They ...

Casting Crowns - Chronik-Fotos - Facebook
Hey Casting Crowns Family, I would appreciate your prayers. Doctors found a solid mass in my right kidney about a week ago. They are 90% sure ...

bubblegum casting (@bgumcasting) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Casting - Quora
Quora is your best source for knowledge.

3d-printer chocolate casting - Flickr - Photo Sharing!
i scanned myself with: www.123dapp.com/catch cleaned and fixed the mesh with: www.netfabb.com/basic.php then subtracted my face from a cube to ...

Voting Machine Caught on Camera Casting Ballot for Democrat when Selecting Republican - YouTube
**UPDATE.... I've heard many reports that this is "just a calibration issue." I will say this... when I went to page 2 and began voting for city ...

'Once Upon a Time' Season 5 spoilers: New casting call hints at flashback scenes
“Once Upon a Time” Season 5 will show two witches while they were still young and innocent. A new casting call for “Once Upon a Time” Season ...

Ridley Scott casting 'tall and agile' Prometheus giants for Alien: Covenant shoot in Sydney
Ridley Scott is on the hunt for tall people to play Engineers and Xenomorphs in his next big-budget science-fiction film, Alien: Covenant. Casting ...

Global Industrial Casting Market Growth of 7.88% - Key Vendors are Alcoa, Dynacast International, Hitachi ...
Research and Markets (http://www.researchandmarkets.com/research/39p8x8/global_industrial) has announced the addition of the &quot;Global Industrial ...

Joseph Fiennes on Michael Jackson casting controversy
Joseph Fiennes is responding to controversy over the news that he will play Michael Jackson

Resources last updated: 2/25/2016 10:58:02 AM