C modern array distribution?

I have code to create a new structure and allocate some space for an array of structures. Initially, I allocate space for 1 structure in the array:

static int datasetCount = 0;

int datasetgroup_new(DatasetGroup *dg char *id){

  dg->id = id;

  // Allocate space for a single dataset to start with
  dg->datasets = (Dataset *) malloc(sizeof(Dataset));

  return 0;

}

Then I have a function to add another structure ('dataset') to the structure containing the array. At the end of the function, I redistribute the array to provide another space:

void datasetgroup_add(DatasetGroup *dg, string filePath){

  // Create the dataset
  Dataset ds;
  dataset_new(&ds, filePath);

  // Copy the dataset to the dataset array
  dg->datasets[datasetCount] = ds;

  // Increment the dataset counter
  datasetCount++;

  //Grow the array
  dg->datasets = (Dataset *)realloc(dg->datasets, sizeof(Dataset) * (datasetCount + 1));

}

I keep reading things that hint that in modern C you don't need to do such things. Maybe I'm wrong ... so is this a more modern / proper way to do this?

Edit:

Sorry to be clear that I am not using C ++ types, I created a typedef for string:

typedef char* string;
+4
source share
2

, C (C11), Glib, , , array.

, , .

linux, brk(), , , , GNU C , realloc() brk(), . valgrind, .

+3

, C, . .

realloc . NULL, . ., , : realloc()

realloc , , (.. datasetgroup_add). / . . , , . , amortized ( ?) .

+3

Source: https://habr.com/ru/post/1584259/


All Articles