Please help me correctly declare a dynamic array. How to make, that if, for example, StartPoint occupies more than 15 characters, 3-4 more characters are added to it? I have a total array size of 50. How can I add 15 more lines when overflowed?

typedef struct { char StartPoint[15]; char StartTime[20]; char EndPoint[15]; char EndTime[20]; char Type[14]; } rover; int p = 0, razm = 50; rover *dat = (rover*)malloc(sizeof(rover)*razm); 
  • > another 3-4 characters were added to it; when overflow, another 15 lines were added Only manually, with reallocation of memory ( realloc() , it seems, but I don’t make much sense in C) and through the function wrappers. If such a need arises often, it may be easier to implement a list where you do not need to re-allocate memory. - etki

2 answers 2

@ masiv1488 , yes, realloc() . Note that the address of the beginning of the array may change.

To implement you need (at least) to store 3 variables. Start address, current size and allocated memory.

You will also need constants (or variables, or a function) for the initial size and increment.

Sometimes it is convenient to combine some of them into a structure, for example:

  struct da { char *body; size_t capacity, length; }; // подобие C++ string 

By the way, the same realloc suitable for initial memory allocation (details in man ).

And do not forget about the final 0 at the end of the line.

    If you allocate memory manually, you need to give up the fixed size, and the structure is honestly redefined as

     typedef struct { char* StartPoint; char* StartTime; char* EndPoint; char* EndTime; char* Type; } rover;