Reputation:
I have two structures-
typedef struct Element
{
int a;
}Element;
typedef struct List
{
Element * E;
}List;
How can I add elements in the array E?I am trying to do this but this is not working-
List list;
list.E=calloc(5,sizeof(int));
for(i=0;i<5;i++)
(list.E+i)->a=2;
What is wrong in this??
Upvotes: 2
Views: 82
Reputation: 53006
Try this
List list;
/* you dont need calloc at all here */
list.E = malloc(5 * sizeof(Element));
if (list.E != NULL) /* check that malloc succeeded before dereferencing the pointer */
{
for (i = 0 ; i < 5 ; i++)
list.E[i].a = 2;
}
you need to allocate 5 * sizeof(Element)
bytes in order to store 5 instances of the struct Element
, and then to access the element you just need the array subscript operator []
.
Note that, sizeof(Eelement) != sizeof(int)
, and that's why your program was not working.
Also, the way your are indexing your array is confusing, the way I show in this answer I think is very easy to follow.
Upvotes: 3