If I think about that like OOP, I would like to get these values:
opt_t[2].size, opt_t[3].elements, opt_t[3].copyElement
How can I do it with C?
Like in 'OOP':
opt_t[2].size
opt_t[3].elements
opt_t[3].copyElement
Did you try it? What went wrong? You don't need to scale pointers by the size of the object in normal C, so the notations like *((&(opt_t->size)+(2*sizeof(struct opt))))
are going in the wrong direction completely. It would be possible to dissect what they are doing, but it is not what was intended and invokes undefined behaviour by accessing memory outside the bounds of what was allocated. (If you really want to know what they do, leave a comment and I'll expound, but you should explain what you think they do in your comment.)
If you wanted to, you could use:
(*(opt_t + 3)).copyElement
You index the pointer, dereference it, and then apply the member access. But it is simpler to use opt_t[3].copyElement
instead.
Also, as I noted in two comments:
Be aware that the _t
suffix is most commonly used to indicate a type name (think size_t
, uint8_t
, wchar_t
etc from the C standard, and many more from POSIX). It would probably be better not to use the suffix on variables; it has the potential to confuse those reading the code. It isn't actually wrong; it just sends the wrong message to people who've seen a lot of C code.
See also Is it a good idea to typedef pointers, to which the succinct answer is 'No' (or 'usually No'). As demonstrated by responses to this question, such typedefs can lead to confusion.
It has also been suggested that there's possibly some confusion about memory allocation in the question. Since it says:
I want to use dynamic allocation and use malloc
to allocate memory of 5 structs of type struct opt
…
and promptly proceeds to demonstrate an acceptable way of doing exactly that, albeit with a cast which many people despise but which doesn't worry me anywhere near as much as it seems to upset other people, I don't see a need to comment further on memory allocation. I quietly assume there will be a call free(opt_t)
or equivalent somewhere when the code has finished with the allocated space — and that if there is space allocated for the elements
members, that space will be freed first.