473,698 Members | 2,450 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

casting of structs

Consider the following code:

struct X { float f; };
struct Y { struct X x; };

void func(struct X *x) {}

int main(void) {
struct Y y;
func(&y);

return 0;
}

Ok, there's two structs. One struct X with some member and struct Y that has
a struct X as the first member. In OO terms we say that Y inherits from X.
Therefore, struct Y can safely be used as a struct X right? Is the above
legal code, can we call func() without casting Y * to X *?
My compiler accepts it without warning and I think it should.
Nov 14 '05 #1
8 5130
"Servé Lau" <i@bleat.nospam .com> spoke thus:
struct X { float f; };
struct Y { struct X x; };
(etc.) My compiler accepts it without warning and I think it should.


cat b.c

struct X { float f; };
struct Y { struct X x; };

void func(struct X *x) {}

int main(void) {
struct Y y;
func(&y);

return 0;
}

gcc -Wall -pedantic -O2 -ansi b.c

b.c: In function `main':
b.c:8: warning: passing arg 1 of `func' from incompatible pointer type

I don't think your compiler is doing you any favors by accepting your
code without issuing a diagnostic.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #2
"Christophe r Benson-Manica" <at***@nospam.c yberspace.org> wrote in message
news:bs******** **@chessie.cirr .com...
I don't think your compiler is doing you any favors by accepting your
code without issuing a diagnostic.


Why not? Is it not true that all pointers to Y can be used as a pointer to
X?
Nov 14 '05 #3
"Servé Lau" <i@bleat.nospam .com> wrote in message
news:bs******** **@news3.tilbu1 .nb.home.nl...

In the context of...
struct X { float f; };
struct Y { struct X x; };
"Christophe r Benson-Manica" <at***@nospam.c yberspace.org> wrote in message
news:bs******** **@chessie.cirr .com...
I don't think your compiler is doing you any favors by accepting your
code without issuing a diagnostic.


Why not? Is it not true that all pointers to Y can be used as a pointer to
X?


No. A pointer to a structure can be portably /converted/ to a pointer to the
first element of the structure and back. Please note the word 'converted'.
On most PC-based platforms, the pointers will even be binary equivalent, but
it does not necessarily have to be the case.

If you want to simulate OOP inheritance in C, do something like:

In the context of...

struct X { /* fileds */ };
struct Y { struct X x; /* more fields */ };
....
type function (struct X *);
....
int main (void)
{
struct Y y;
func(&y.x); /* note .x */
return 0;
}
Nov 14 '05 #4
In article <bs**********@n ews3.tilbu1.nb. home.nl>,
Servé Lau <i@bleat.nospam .com> wrote:
[one "struct" contains another whole, so that &y.x has type "struct X *",
and:]
void func(struct X *x) {}

int main(void) {
struct Y y;
func(&y);

return 0;
}

Ok, there's two structs. One struct X with some member and struct Y that has
a struct X as the first member. In OO terms we say that Y inherits from X.
In "proper" OO terms the member named y.x (of type "struct X")
should be able to go anywhere, not just first.
Therefore, struct Y can safely be used as a struct X right?
In C89 and C99, only via conversions.
Is the above legal code, can we call func() without casting Y * to X *?
My compiler accepts it without warning and I think it should.


C89 and C99 both require diagnostics.

Plan 9 C, which is a different language from both C89 and C99,
allows this kind of call. It works even if "y.x" is not the
first member, too -- the call has the same effect as func(&y.x).
However, the definition for struct Y must read rather differently:

struct Y {
int any, stuff, you, like;
struct X; /* inherit all of struct X's members */
int more, things, ifdesired;
};

I am not quite sure what Plan 9 C says must occur if "struct X"
has members whose names conflict with those of "struct Y" (exclusive
of "struct X" of course). Moreover, what does it mean if you
try to inherit from the same datatype more than once? For
instance:

struct Point { int x, y; };

struct Rectangle {
Point; /* e.g., upper left corner */
int w, h; /* width and height */
};

is OK, but what about:

struct Rectangle {
Point;
double x; /* error? ok? */
};

and clearly:

struct Rectangle {
Point; /* upper left */
Point; /* lower right */
};

is right out. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5
"Servé Lau" <i@bleat.nospam .com> wrote:
Consider the following code:

struct X { float f; };
struct Y { struct X x; };

void func(struct X *x) {}

int main(void) {
struct Y y;
func(&y);
This line is a constraint violation, a conforming compiler must
issue a diagnostic for the code. For example:
slau.c:8: warning: passing arg 1 of `func' from incompatible pointer type
return 0;
} Ok, there's two structs. One struct X with some member and struct Y
that has a struct X as the first member. In OO terms we say that Y
inherits from X. Therefore, struct Y can safely be used as a struct
X right?
Yes, it can, so long as you convert the pointer properly.
Is the above legal code, can we call func() without casting
Y * to X *? My compiler accepts it without warning and I think
it should.


No, you must use a cast to convert from Y* to X*. Any compiler that
accepts it without a diagnostic (either warning or error) is not
a standard-conforming compiler or not being invoked with the right
options (such as GCC's -ansi -pedantic).

--
Simon.
Nov 14 '05 #6
On Fri, 26 Dec 2003 20:44:59 +0100, "Servé Lau" <i@bleat.nospam .com>
wrote in comp.lang.c:
Consider the following code:

struct X { float f; };
struct Y { struct X x; };

void func(struct X *x) {}

int main(void) {
struct Y y;
func(&y);

return 0;
}

Ok, there's two structs. One struct X with some member and struct Y that has
a struct X as the first member. In OO terms we say that Y inherits from X.
There are no OO terms in C.
Therefore, struct Y can safely be used as a struct X right? Is the above
legal code, can we call func() without casting Y * to X *?
My compiler accepts it without warning and I think it should.


Either your compiler is broken, or you are using it in a
non-conforming mode.

C is a typed language. Regardless of location in memory, a pointer to
a struct X is not a pointer to a struct Y or a pointer to a float.

--
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.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 14 '05 #7
Peter Pichler <pe***********@ tiscali.co.uk> spoke thus:
No. A pointer to a structure can be portably /converted/ to a pointer to the
first element of the structure and back.


FMI, can you quote the portion of the Standard that allows this?
Consider my curiousity piqued :)

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #8
Christopher Benson-Manica wrote :
Peter Pichler spoke thus:
No. A pointer to a structure can be portably /converted/ to a pointer to the first element of the structure and back.


FMI, can you quote the portion of the Standard that allows this?
Consider my curiousity piqued :)


Ehm, did I manage to make a fool of myself /again/? ;-)

No quote, just my simplified interpretation of 6.7.2.1:
....
13 Within a structure object, the non-bit-field members and the units in
which bit-fields reside have addresses that increase in the order in
which they are declared. 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. There may be
^^^^^^^^^^^^^^
unnamed padding within a structure object, but not at its beginning.
Nov 14 '05 #9

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

Similar topics

5
3125
by: Paminu | last post by:
Why make an array of pointers to structs, when it is possible to just make an array of structs? I have this struct: struct test { int a; int b;
7
2076
by: Marc W. | last post by:
I have been trying to cast an object I am getting from a SortedList for some time now, into the object it is supposed to be, but it just won't work. Here is the code: (StudentLocation)(student.stuSchedules).lo cation = txtRoom.Text; Every object in the stuSchedules array is a StudentLocation object. However, SortedLists store all of their values as objects, so I need to convert it back into the correct type so I can set one of the...
4
4504
by: kelli | last post by:
i am new to c# so if this is a trivial problem, forgive me! i've searched the web and after 2 days still cannot solve it. i am converting a c++ application to c# - the problem code is listed below. the c++ code uses a byte array (msg) to hold a serial message. since the message can be of different layouts, the array is cast to the appropriate layout "type" (struct SERIAL_CAN_MSG_TYPE, in this example). to complicate things, there is an...
14
5191
by: Yurik | last post by:
A question to the C# language experts: Why isn't this code valid? static void Foo( out string s ) { s = "test"; } static void Main( ) { object s; // *** Accept any out type!
44
2215
by: Agoston Bejo | last post by:
What happens exactly when I do the following: struct A { int i; string j; A() {} }; void f(A& a) { cout << a.i << endl;
17
2568
by: goldfita | last post by:
I saw some code that appeared to do something similar to this struct foo { char offset; int d; }; struct foo { int a; int b;
8
5078
by: tom | last post by:
Hi All, I'm stuck whit an issue I can't seem to resolve in C#: I have an arry of bytes which I would like to "recast" to an array of structs with an Explicit layout. I tried the Buffer.BlockCopy method, but that one complains my struct is not a primitive type. Any Suggestions ?
23
2496
by: Leif Gruenwoldt | last post by:
Is it possible to safely cast a struct to a class? The contents of both are the same size, however there is the issue of the class having virtual functions which make the size of the class slightly larger.
61
3753
by: Marty | last post by:
I am new to C# and to structs so this could be easy or just not possible. I have a struct defined called Branch If I use Branch myBranch = new Branch(i); // everything works If I use Branch (myBranch + x) = new Branch(i); // it doesn't x is a loop iterator, i is an int for the constructor to define an array. What am I doing wrong here.
0
8604
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
9160
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
8862
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
7729
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
6521
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
4370
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...
1
3050
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
2
2331
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2002
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.