3

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

devoidfeast
  • 829
  • 3
  • 12
  • 22

5 Answers5

7

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));
casablanca
  • 69,683
  • 7
  • 133
  • 150
  • +1 for complete answer, but is that realloc() portable? I mean, I tried that too, but sometimes I get an error and sometimes it works. Same conditions, same system, same data. – BlackBear Dec 13 '10 at 18:25
  • @BlackBear: Yes, it's very much portable. What kind of error did you get? – casablanca Dec 13 '10 at 18:30
  • Resource leak. A sort of. I don't have that source anymore. – BlackBear Dec 13 '10 at 18:34
  • @BlackBear: if you didn't allocate memory for your structs' members, then you really should have any resources left out when you free that pointer. – haylem Dec 14 '10 at 00:27
  • In this code, if `realloc` can't allocate enough memory, you have a memory leak. I think take into a temporary variable and check it before assigning to `array`. – Navaneeth K N Dec 14 '10 at 04:29
1

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

1

I have a dynamically growing string buffer implementation. You can get it from here. It uses the same malloc and realloc technique.

Navaneeth K N
  • 15,295
  • 38
  • 126
  • 184
0

Look at realloc function from the standard library.

Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96
0

Look up malloc?

Squirrelsama
  • 5,480
  • 4
  • 28
  • 38