element_p
must be a pointer to struct Element
but hello->data
is int data[1]
, so you need the cast. Suppose you initialized hello
you "force" element_p
to be a pointer to an area of memory where a single integer is, since in fact hello->data
will point to the first and only integer "contained" in the array hello->data[]
. Since struct Element
"contains" 2 integer, element_p->a
should access to hello->data[0]
, but element_p->b
would try to accesso to hello->data[1]
which is out of the bound of the array.
The for loop will copy data of the size of the struct Element (very likely 2*sizeof(int)
), taken from each initialazed struct element_
, into the are pointed by element_p
that, as we've said and because of a missing part (see hack below), have room for just 1 int. Since element_p
stays the same, you will overwrite that memory and only the last "struct" copied will survive.
As you showed to us, it looks like a good recipe for a crash. Anyway if the hack
Joe talks in comment about is in place, element_p
will point to the first int of several other "ints". Since ints are nothing but memory, they could be enough to accomodate struct Element
structs you could access with element_p[0]
the first, element_p[1]
the second and so on. Likely something like
hello = malloc(sizeof (*hello) + sizeof (struct Element) * 6);
or alike. Now, element_p = (struct Element *)hello->data
can be used.
Anyway the for loop continues to write over the same area, element_p
needs to be advanced by 1 (1 whole struct Element
) in order to fill each time a different area (element_p+i
shoudl go).