How does C store global struct variables? Also, if I try to assign a smaller struct object to a pointer of a larger struct? Basically this:
struct A{
int a;
};
struct B{
int b;
};
struct C{
struct A a;
struct B b;
};
struct A aa;
struct C * c = (struct C*) &aa;
What memory location does c->b gets to point to?
I tried a basic example and it seems, no matter in what order I declare/initialize two variables, the compiler is always coupling s1 to s3 in the following example:
#include <stdio.h>
struct One{
int a;
int b;
} s2,s1,*sp1;
int e;
int ff;
struct Two{
int c, d;
} q,r,t, s4,s3;
struct Three
{
struct One one;
struct Two two;
};
int main()
{
e=1;
sp1=&s1;
sp1->a=1;
s4.c=22;
s3.c=10;
struct Three * ll = (struct Three *) sp1;
ll->two.c = 1000;
printf("\n%d\t%d", s3.c, s4.c);
return 0;
}
Does anyone have an idea on why it might be happening? Link for running/output: https://www.ideone.com/YP4Y1e
Edit:
Thanks everyone, I understand this is bad coding practice. But I was more puzzled since in the full code example I gave, compiler was always putting s1 and s3 together in memory so my pointer ll->two had data from s3.
But it seems it is readonly. If I change value of ll->two.c the same is not reflected in s3.c. That lead me to believe that compiler might be copying the data to some other location in memory and ll might not be assigned a contiguous block of memory.
Is this behavior expected? You can read random block of memory with a bigger pointer type but cannot write to it? Or it is just undefined behavior as well?