Click here to Skip to main content
15,038,237 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I know the way to access the members of structure using . or -> operator.
I can access members of array using base pointer for example:
C
int array[8];
printf("%d", array+1); // Will print element at 1 st place in array

How can I access element of a structure using base pointer, maybe something like this:

C
struct st
{
    int i;
    int j;
};
struct st strcture;
*(&structure+1) = 100;          // This gives some error
printf("%d", &structure+1);     // Should print the value of i of st that is 100 but some garbage is returned

Am I clear with my question? How can I do it?

Thanks
Vicky
Posted
Updated 3-Jun-10 0:33am
v2

You should properly cast the pointer (you know, pointer arithmetic...).
For instance
C
#include <stdio.h>
struct st
{
  int i;
  int j;
};
int main()
{
  st a = {5,11};
  st * pa = &a;
  int first, second;
  first = *((int*)pa);
  second = *((int*)pa +1);
  printf ("first=%d,second=%d\n", first, second);
  return 0;
}

:)
   
v2
Comments
vikasvds 3-Jun-10 10:21am
   
Thank you very much!!
Your explanation cleared my doubt.
Thanks again.
CPallini has given you the answer. But be aware of something called 'structure padding'. Look it up.
   
At the risk of sounding like the daft paper clip that used to give you advice in Microsoft Office...

"Hey, it looks like you want to access a structure field through a pointer and offset..."

In C you're forced to use something that's got loads of casts in it - there was an example of how to do that in a previous answer. As another answer mentioned you might have stucture alignment issues.

If you're using C++ you can use pointers to members which gives you all the goodness of offsets into a structure without running into problems with alignment.

Say you've got a structure B:

struct B
{
    int i;
    int j;
};


You can declare a pointer to either of the members using the following syntax:

int B::*p = &B::i;


Which says you can access one of the integers in the structure relative to the starting address of one of the structures. e.g:

B b;

B *pb = &b;

pb->*p = 100;


The last statement sets the i member of b to be 100, indirectly.

This is particularly handy when you want to iterate through an array of structures modifying a variable member of the structure...

e.g.

int B::*members[2] = { &B::i, &B::j };


You can then switch between members of the structure depending on which one of the members you access:

pb->*members[0] = 50;


It gets even cooler when you start using member function pointers, but that's another story.

Cheers,

Ash
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900