1

I have 2 sructures :

struct b{int b;float d;}; and 
struct a{int count; struct b* ptr;}
struct a *a_temp;

Now i allocate memory for 10 strucutures of type b and put the address in ptr of struct a. (the code was given to me and they didnt want to use double pointer for some reason)

a_temp = (struct a*)malloc(sizeof(struct a));
a_temp->ptr = (struct b*)malloc(10*sizeof(struct b));
struct b* b_temp;

I have to load the address of second structure of type b to temp_b. I tried b_temp = a_temp->ptr[1]; which is giving error but b_temp = &(a_temp->ptr[1]); is working when i try to use this and access contents of structure b using this,why is this?

thanks in advance

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
user1023527
  • 41
  • 2
  • 7

1 Answers1

3

ptr[1] is structure, pointed by ptr + 1 (just like *(ptr+1)), b_temp gets a pointer to structure, so you have to pass the address of a_temp->ptr[1], which is &a_temp->ptr[1].

expression      | type
---------------------------
a_temp->ptr     | struct b*
a_temp->ptr[1]  | struct b
&a_temp->ptr[1] | struct b*
a_temp->ptr + 1 | struct b*
b_temp          | struct b*

Edit:

if you have a pointer, lets say int * x, then the following expressions are identical: x[1] and *(x+1), and they both deference the address x+1. in other words, those expressions value is the type of variable that the pointer x points to, in this case it is an int, since x is int * (pointer to int) it holds an address to an int variable.

hugomg
  • 68,213
  • 24
  • 160
  • 246
MByD
  • 135,866
  • 28
  • 264
  • 277
  • Hi thanks for the quick reply,I understand that a_temp->ptr is a pointer to structure of type b, but i dont get how a_temp->ptr[1] becomes a structure , it will be really great if you can please explain this a little more.I thought ptr[1] will contain the address of second structure created by allocation ie ptr will just contain the base address of allocation and when we do ptr[1] it will just add 1*(size of structure) to get the addres of next structure.Please correct me – user1023527 Nov 01 '11 at 12:46
  • Hi thanks I get it ,If possible can you please help me to do the same using double pointers.. – user1023527 Nov 01 '11 at 12:51