Please post the structures.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
As you can see that this code is accessible in turbo C but not in Dev C++
That's because Dev-C++ is properly disallowing a language constraint violation. The address-of operator may only be used on an lvalue. You can use offsetof() to avoid the very hackish calculations that your awful book is encouraging:
#include <stdio.h>
#include <stddef.h>
struct a {
struct b {
int i;
float f;
char ch;
} x;
struct c {
int j;
float f;
char ch;
} y;
} z;
void fun(struct c *p)
{
/* Find the offset of the struct c member */
size_t offset = offsetof(struct a, y);
/*
Find the base address of the struct b member
since we know it precedes the struct c member
*/
struct b *address = (struct b*)((char*)p - offset);
/* Hope and pray that what we "know" about struct a is correct */
address->i = 400;
address->f = 3.14;
address->ch = 'c';
}
int main(void)
{
fun(&z.y);
printf("\n%d %f %c", z.x.i, z.x.f, z.x.ch);
return 0;
}
It's still silly and unsafe, but at least the code should build and run on a modern compiler.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Hello everyone!!
I am new to Linux forum and have a question related to typecasting in C related to offset of structures.
Typecasting is something that happens to actors...
Trentacle
Junior Poster in Training
72 posts since Dec 2010
Reputation Points: 110
Solved Threads: 20