Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Growing Array in C [closed]

Tags:

c

Can any one Explain me plz the concept of Growing Array Of Structs. i mean dynamic Arrays. thanks for your Time.

like image 709
devoidfeast Avatar asked Jun 25 '26 19:06

devoidfeast


2 Answers

Start with a small array of some size, then whenever you need to increase the size, use realloc to do so; it is common to double the size of the array whenever you resize it.

For example:

int length = 5;
my_struct *array = NULL;

/* Initialization */
array = (my_struct *)malloc(length * sizeof(my_struct));

/* Use array[0] .. array[length - 1] */

/* When you reach the limit, resize the array */
length *= 2;
array = (my_struct *)realloc(array, length * sizeof(my_struct));
like image 102
casablanca Avatar answered Jun 27 '26 08:06

casablanca


Do you mean dynamic size of an array? In that case you must allocate memory fitting for you needs. See realloc

like image 24
Mikkel Lund Avatar answered Jun 27 '26 09:06

Mikkel Lund