Re: Question on accessing structure
- From: vippstar@xxxxxxxxx
- Date: Thu, 31 Jan 2008 03:58:43 -0800 (PST)
On Jan 31, 1:52 pm, Sid <Sid4C...@xxxxxxxxx> wrote:
All,Because it invokes undefined behavior, you pass a pointer to A where a
See the below piece of C code snippet
typedef struct _a
{
int ia;
int ja;
}A;
typedef struct _b
{
int ib;
int jb;
}B;
typedef struct _x
{
A a;
B b;
}X;
void func(X *ptr)
{
ptr->b.ib = 10;
ptr->b.jb = 20;
ptr->a.ia = 48;
ptr->a.ja = 50;
}
main()
{
A *temp = (A*)malloc(sizeof(A));
func(temp);
printf("%d\n",((X*)temp)->b.ib);
}
why does not the above program result in segmentation error.
pointer to X is expected.
I am just allocating memory for structure A and typecasting it toYour program most likely writes to memory you have access to, but as
structure X and writing value to its members i.e Structure A and
structure B.
I compiled above program with MS VC++ and gcc ...it just gives me
warning and not runtime error as well.....and o/p is right.....
far as C is concerned, you invoke undefined behavior and anything can
happend after that.
.
- References:
- Question on accessing structure
- From: Sid
- Question on accessing structure
- Prev by Date: Question on accessing structure
- Next by Date: Re: Strange C operator
- Previous by thread: Question on accessing structure
- Next by thread: Re: Question on accessing structure
- Index(es):
Relevant Pages
|