tags:

views:

503

answers:

4

the follwing code is run successfully ...

typedef struct _s
{
  int *r;

}s;

void main()
{
   s *u;
   int y=1000;  
   u=malloc(sizeof(s)*8);
   u->r=malloc(sizeof(int)*8);
   u->r[5]=y;

   printf("%d\n",u->r[5]);
   getch();
}

but i write the follwing code as above but gives error ....i use structure.....may why i know the reason....? if i use double pointer like (...e **h...) produces correct output... but the reason is...?

typedef struct _e
{
   int r;
}e;

typedef struct _s
{
  e *h;

}s;

void main()
{
   s *u;
   int y=1000;   
   u=malloc(sizeof(s)*8);

   u->h=(e*)malloc(sizeof(e)*10);
   u->h[1]=y;
   printf("%d\n",u->h[1]);   
   getch();
}
+1  A: 
u->h[1]=y;

Is an attempt to assign an int to a struct. Instead it should be

u->h[1].r=y;

And the same goes for printf().

sharptooth
+4  A: 

You are trying to assign an integer to a struct:

int y=1000;   
u->h[1]=y;

Probably you wanted to use u->h[1].r (and also in the following print statement):

u->h[1].r=y;
printf("%d\n",u->h[1].r);

If h would be declared as e** it doesn't give any errors because u->h[1] is then of type e* and the int y can be implicitly converted to a pointer in the assignment. But that wouldn't really do anything useful.

sth
A: 

First of all, why are you doing this? It doesn't make sense to have one-letter names, nor structures with a single element.

s is a type representing a structure containing a single pointer-to-e, which is in turn a type containing a single int.

u is a pointer to an s, and thus u->h[1] is of type e. You can not assign a int to an e. The only reason it seems to work with **h is because you are assigning an int to a pointer, which is possible but almost always wrong.

Matthew Flaschen
+1  A: 

In the line

u->h[1]=y;

the left hand side is a struct, not an integer. Write

u->h[1].r=y;

and you assign y to the field r of the struct, which is what you intend to do.

Pim