4 ms·
What is the benefit of using a zero sized array over a pointer?
by hiimnate 10y ago
What is the benefit of using a zero sized array over a pointer?
- amq 10y agoWhen using shm_open and mmap there hardly is a shorter solution.
- halayli 10y agoyou 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
- Koshkin 10y agoI guess the simplest example is struct header { size_t size; char data[0]; }, where 'data' simply labels the beginning of what follows the 'header'.
- Gibbon1 10y agoI do that all the time, packets come in, packets go out. They have headers and 'data'. A lot of code that deals with the header information does not need to know anything about the data part.