pointer to structure from pointer to member

S

sieg1974

Hi,

Given a pointer to a member within a struct, is it possible to
determine the pointer to the structure? If so, how can it be done?

Thanks,

Andre

struct Structure
{
....
int Integer;
....
};

struct Structure * get_pStructure( int *pInteger )
{
....
}
 
F

Frederick gotham

sieg1974 posted:


Maybe something like:

#include said:
struct Structure
{
...
int Integer;
...
};

struct Structure * get_pStructure( int *pInteger )
{


return (struct Structure*)
((char*)pInteger - offsetof(Structure,Integer));
 
S

shaanxxx

Frederick said:
Correction:

offsetof(struct Structure,Integer)

#include<stdio.h>

#define offsetof(a,b) (&((a *)0 )->b)

typedef struct xxx{
int a;
int b;
int c ;

}ttt;

int main()
{
printf("%d\n", offsetof(struct xxx,a));
printf("%d\n", offsetof(struct xxx,b));
printf("%d\n", offsetof(struct xxx,c));
}
 
J

J. J. Farrell

shaanxxx said:
#include<stdio.h>

#define offsetof(a,b) (&((a *)0 )->b)

typedef struct xxx{
int a;
int b;
int c ;

}ttt;

int main()
{
printf("%d\n", offsetof(struct xxx,a));
printf("%d\n", offsetof(struct xxx,b));
printf("%d\n", offsetof(struct xxx,c));
}

I don't know what you're trying to say in this message, but this
results in undefined behaviour. offsetof() is a Standard macro defined
in <stddef.h>; there's no reason to define a macro of the same name
other than to introduce bugs or reduce portability.
 
S

shaanxxx

Actually i checked with man page, i didnt find there so i thought it is
not in standard(wrong thoughts). I AM NOVICE TO "C" langauge.
 
J

Jack Klein

Actually i checked with man page, i didnt find there so i thought it is
not in standard(wrong thoughts). I AM NOVICE TO "C" langauge.

THEN DON'T ANSWER QUESTIONS HERE UNTIL YOU ARE AN EXPERT.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top