Reputation: 23
I am attempting to use a set of nested structures; one which defines a single co-ordinate in 3D (coordinate
) and one which describes certain properties about a rectangle (rectangle
). The number of rectangles dynamically changes at runtime and malloc is successfully working to assign the rectangle structure array. My issue lies within using the nested structure arrays (Face_Close
and Face_Far
) of a fixed size of 4 items, which I can't seem to allocate / use successfully.
Nested structures:
//co-ordinate structure
typedef struct coordinate
{
double X;
double Y;
double Z;
} coordinate;
//rectangle
typedef struct rectangle
{
coordinate Face_Close[4];
coordinate Face_Far[4];
coordinate Rotation_Centre;
coordinate Normal_To_Plane;
} rectangle;
I am allocating the outer structure to a dynamic sized portion of memory using a pointer:
struct rectangle **cellArray;
The memory for cellArray
gets successfully allocated and defined at runtime using:
cellArray = (rectangle**) malloc(num_Cells * sizeof(rectangle*));
While I can assign elements of a singular nested structure instance by using:
cellArray[currentCell]->Rotation_Centre.X = X_value;
cellArray[currentCell]->Rotation_Centre.Y = Y_value;
cellArray[currentCell]->Rotation_Centre.Z = Z_value;
I can't seem to use the inner structure array for Face_Close
or Face_Far
; my code compiles successfully with no warnings but generates a SIGSEGV (Mem Error) error during runtime when attempting either:
cellArray[currentCell]->Face_Close[1]->X
or
cellArray[currentCell]->Face_Close[1].X
I have tried the following already:
coordinate Face_Far[4];
to coordinate *(Face_Far[4]);
however this also gives SIGSEGV (Mem Error).coordinate Face_Far[4];
to int *Face_Far[4];
and using it as a pointer array which also gets allocated using malloc using cellArray[currentCell]->Face_Close = (coll_rect_coord**) malloc(4 * sizeof(coll_rect_coord *))
however this also gives SIGSEGV (Mem Error).coordinate Face_Far[4];
to int *Face_Far[4];
and attempting to assign the value the pointer references by cellArray[currentCell]->Face_Close = &(coll_rect_coord**) malloc(4 * sizeof(coll_rect_coord *))
which restults with an error lvalue required as unary '& operandUpvotes: 2
Views: 289
Reputation: 144989
You allocate an array of pointers to rectangle
structures, but you do not make these pointers point to actual structures, allocated of not. In fact these pointers are uninitialized, so dereferencing them has undefined behavior: in your case a segmentation fault.
You should allocate the structures, or make cellArray
a pointer to an array of rectangle
and allocate it appropriately:
struct rectangle *cellArray;
cellArray = malloc(num_Cells * sizeof(*cellArray));
If currentCell < num_Cells
you would write:
cellArray[currentCell].Rotation_Centre.X = X_value;
cellArray[currentCell].Rotation_Centre.Y = Y_value;
cellArray[currentCell].Rotation_Centre.Z = Z_value;
cellArray[currentCell].Face_Close[1].X = X_value;
...
Upvotes: 1