I have found many 'pointer becomes NULL' questions, but struggling to apply the answers to my problem
I have 3 nested structs. Struct A should contain an array of struct B, which contains a single struct C which itself should contain an array of int:
typedef struct {
int32_t *data;
uint16_t nData;
uint16_t dataOffset;
} Window;
typdef struct {
Window *window;
const char *datasetPath;
} Dataset
typedef struct {
char *id;
uint8_t count;
Dataset *datasets;
} DatasetGroup;
I have a new function for the structs:
int8_t dataset_new(Dataset *ds, const char *datasetPath, uint16_t winSize){
ds->datasetPath = datasetPath;
ds->window = malloc(sizeof(*(ds->window));
ds->window->data = malloc(sizeof(int32_t) * (winSize));
return 0;
int8_t datasetgroup_new(DatasetGroup *dg, char *id){
dg->id = id;
dg->count = 0;
dg->datasets = malloc(sizeof(*(dg->datasets)) * 255);
}
And I have an add function to add a Dataset to the DatasetGroup:
int8_t datasetgroup_add(DatasetGroup *dg, const char *filePath, uint16_t winSize){
// Create the dataset
Dataset ds;
dataset_new(&ds, filePath, winSize);
// Add the dataset to the dataset array
dg->datasets[dg->count] = ds;
dg->count++;
return 0;
}
I then iterate through the datasets in order to populate the data, doing stuff like:
for (i = 0 ; i < datasetCount ; i++){
Dataset *ds = &(dg->datasets[i])
Always on the 2nd interation, the data array becomes a null pointer:
data = ds->window->data
I understand that I have done something wrong passing pointers around(?) but I'm not sure what precisely I have done wrong....
&dg->datasets[1].window->data).datasetgroup_add()you are declaringdson the stack, which can/will get overwritten oncedsgoes out of scope when you return fromdatasetgroup_add(). Try movingdsto the heap.ds.windowandds.datasetPathare getting overwritten, i.e. the memory location where you are declaringdsis being reused for other stuff. Try changingdsto a pointer that you thenmallocand see if that fixes it.