I need to get a pointer to a particular member variable of a structure

Here's what i have done

typedef struct
{
int var1;
other variables ... 
} structname;

---some other code here---

structname* structptr;
int* intptr;
intptr=(int*)&(structptr->var1)

but this isn't working. What's the correct way to do this

Well I am not able to point out your mistakes exactly but this code does work:

#include<stdio.h>

struct node{
int a;
char b;
};

typedef struct node * NODE;

int main()
{
NODE n;
int *in;
char *ch;
n=(NODE)malloc(sizeof(struct node*));
in=&(n->a);
ch=&(n->b);
*in=10;
*ch='a';
printf("%d %c",*in,*ch);
return 0;
}

I think the way in which you have defined the typedef of the struct is wrong.

Apart from that the initialization of pointer for struct or creating the sruct of some type as

<struct name> variable;

doesn't make the structure usable. You need to allocate memory for the structure using malloc as mentioned above.

Thanks for the help. It worked for me

Related to: n=(NODE)malloc(sizeof(struct node*)); Casting malloc is not necessary if the proper header file stdlib.h is included.
Fail to check for a successful return of allocated memory.
Fail to release dynamic memory.

The code indentation has room to improve.

Related to: n=(NODE)malloc(sizeof(struct node*)); Casting malloc is not necessary if the proper header file stdlib.h is included.
Fail to check for a successful return of allocated memory.
Fail to release dynamic memory.

Yes the code is not complete it lacks other details too like the actual usage of pointers to other important things has not been shown.

it should end with free(n);

and should possess error check as you said.

Can you be a bit more descriptive in your explanation of first point.?

>Can you be a bit more descriptive in your explanation of first point.?
Some more explanation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.