You bet wrong, Tux0r - it's not undefined behaviour, unless you try to access non-existent array elements, but it is an ugly hack from the early days of C.
The struct rsp has a zero-element array. However, if you dynamically allocate memory like this;
Code:
#include <stdlib.h>
/* sanddune's declarations */
int main()
{
rsp *with_two = malloc(sizeof(rsp) + 2 * sizeof(statusrecord));
if (with_two != NULL)
{
/* effectively with_two points at an rsp object that has two statusrecords */
with_two->stRec[0].a = 5; /* OK as we have two statusrecords */
with_two->stRec[0].ch = 'A'; /* OK as we have two statusrecords */
with_two->stRec[1].a = 5; /* OK as we have two statusrecords */
with_two->stRec[1].ch = 'A'; /* OK as we have two statusrecords */
with_two->stRec[2].a = 5; /* Undefined behaviour as we have only two statusrecords */
with_two->stRec[2].ch = 'A'; /* Undefined behaviour as we have only two statusrecords */
free(with_two);
}
return 0;
}
The (claimed) advantage of this is that only one malloc() call is needed. If stRec was declared as a pointer, it would be necessary to do this.
Code:
int main()
{
rsp *with_two = malloc(sizeof(rsp) + 2 * sizeof(statusrecord));
if (with_two != NULL)
{
with_two->stRec = (statusrecord *)((char *)rsp + sizeof(rsp));
/* other manipulations of elements of with_two->stRecstuff as per previous example */
free(with_two);
}
}
or
Code:
int main()
{
rsp *with_two = malloc(sizeof(rsp));
if (with_two != NULL)
{
with_two->stRec = malloc(2*sizeof(statusrecord));
if (with_two->stRec != NULL)
{
/* other manipulations of elements of with_two->stRecstuff as per previous example */
free(with_two->stRec);
}
free(with_two);
}
}