4 ms·
you can do x = malloc(sizeof x + <variable_length)) x->zero_array points to the variable_length. The advantage is that you get contiguous memory access and d
by halayli 10y ago
you can do
x = malloc(sizeof x + <variable_length))
x->zero_array points to the variable_length.
The advantage is that you get contiguous memory access and do a single malloc.
As opposed to:
x = malloc(sizeof x)
x->ptr = malloc(<variable_length>);
x and ptr are not necessarily contiguous.
- hiimnate 10y agoBut can't you write it so that it is contiguous using a pointer?
- jmpeax 10y agoYou can x = malloc(sizeof(x) + <variable_length>); x->ptr = x + sizeof(x);
- imron 10y agoExcept it requires sizeof a pointer more memory and an extra assignment after the malloc, which is why people use the zero-sized array instead (note this comment was to explain for the grandparent why you would normally prefer a zero-sized array instead).
- imron 10y agoNo, because a pointer points to some location in memory, not whatever follows the memory after the location of the pointer. See [0] for a picture. [0] http://c-faq.com/aryptr/aryptr2.html http://c-faq.com/aryptr/aryptr2.html