I am trying to create a dynamic 3D array to store 3 graphics points [x, y, z] in each location (hence the use of a struct).
array[i][j][k]
The i & j dimentions store the frame data.
The k dimension is needed because the data values change for each frame of the image.
At the beginning of the program all values are unknown hence the use of dynamic arrays, and all data is read from a file.
The reason i need to use realloc is that to start with i only know the x & y dimensions so i can read in the initial frame data (as such i have only initially allocated 1 frame) but once the initial frame is read in i can then read the actual number of frames and have to then resize the array in the k dimension.
The problem im having is that the
Code:
skeleton[i] = realloc(*skeleton[i], (num_allocated_hierarchy_y * sizeof(OFFSET *)));
line is segfaulting.
any help would be much appreciated???
Code:
// Skeletal Structure
typedef struct {
double x;
double y;
double z;
double angle;
int used;
} OFFSET;
OFFSET *** skeleton = NULL;
OFFSET *allElements = NULL;
int num_elements_hierarchy_x = 0, num_elements_hierarchy_y = 0, num_elements_frames = 0;
int num_allocated_hierarchy_x = 0, num_allocated_hierarchy_y = 0, num_allocated_frames = 0;
int array_size_frames = 1;
int array_size_hierarchy = 0;
void Add_Skeleton() {
if(num_elements_hierarchy_x == num_allocated_hierarchy_x || num_elements_hierarchy_y == num_allocated_hierarchy_y || num_elements_frames == num_allocated_frames) { // Are more refs required?
if (num_allocated_hierarchy_x == 0) {
num_allocated_hierarchy_x = array_size_hierarchy;
} else {
num_allocated_hierarchy_x *= 2; // Double the number of refs allocated
}
if (num_allocated_hierarchy_y == 0) {
num_allocated_hierarchy_y = array_size_hierarchy;
} else {
num_allocated_hierarchy_y *= 2; // Double the number of refs allocated
}
if (num_allocated_frames == 0) {
num_allocated_frames = array_size_frames;
} else {
num_allocated_frames *= 2; // Double the number of refs allocated
}
// Array Iterators
int i, j;
// Allocate 3D Array
allElements = realloc(allElements, (num_allocated_hierarchy_x * num_allocated_hierarchy_y * num_allocated_frames * sizeof(OFFSET)));
skeleton = realloc(skeleton, (num_allocated_hierarchy_x * sizeof(OFFSET **)));
for(i = 0; i < num_allocated_hierarchy_x; i++) {
skeleton[i] = realloc(*skeleton[i], (num_allocated_hierarchy_y * sizeof(OFFSET *)));
for(j = 0; j < num_allocated_hierarchy_y; j++) {
skeleton[i][j] = allElements + (i * num_allocated_hierarchy_y * num_allocated_frames) + (j * num_allocated_frames);
}
}
// If the reallocation didn't go so well,
// inform the user and bail out
if (!skeleton) {
fprintf(stderr, "ERROR: Couldn't realloc memory!\n");
return;
}
}
printf("Allocated!\n");
return;
}