Re: Basic C query.
Re: Basic C query.
- Subject: Re: Basic C query.
- From: Jamison Hope <email@hidden>
- Date: Wed, 23 Jun 2010 11:21:03 -0400
On Jun 23, 2010, at 10:53 AM, Arnab Ganguly wrote:
Dear All,
Sorry for posting a basic C question.Below is the code base.
struct Test
{
int a;
int b;
};
//member offset.
int result = (((Test *) 8)->a) - 8;
I get bus error for this. I am not clear about the logic as what
exactly ((Test *) 8)->a signifies here and why -8 is done.
You're taking the number 8 and casting it as a pointer to a Test.
You're then taking this alleged Test* and accessing the member field
called "a", which is an int, and subtracting 8 from it, storing the
difference in "result". The -8 is a red herring; the reason you're
getting a bus error is that the memory at address 8 does not, in fact,
contain a Test structure, but rather some kernel stuff you aren't
allowed to touch from user code.
[Incidentally, if this is actually vanilla C and not C++, there should
be a "typedef struct Test Test;" somewhere as well in order to
associate the Test in "((Test *) 8)" with struct Test.]
This would work:
#include <stdint.h> /* for intptr_t */
#include <stdio.h> /* for printf */
struct Test
{
int a;
int b;
};
typedef struct Test Test;
int main(void) {
Test t;
t.a = 10;
intptr_t an_integer = (intptr_t)&t;
int result = (((Test *) an_integer)->a) - 8; /* notice I am using a
known address and not an integer literal */
printf("result: %d\n", result);
return 0;
}
-Jamie
--
Jamison Hope
The PTR Group
www.theptrgroup.com
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden