Can any one Explain me plz the concept of Growing Array Of Structs. i mean dynamic Arrays. thanks for your Time.
Asked
Active
Viewed 4,109 times
3
-
What exactly do you need help with? – Karl Knechtel Dec 13 '10 at 18:00
-
14You need to make sure it gets plenty of sunlight and water it regularly – Falmarri Dec 13 '10 at 18:01
-
I'm sure wiki explains it much better than someone here would care to. Why don't you read it and ask here a specific question? – ruslik Dec 13 '10 at 18:02
-
Lookup Dynamic Array (like vector, ArrayList) on Wikipedia. That should get you started. – Sonny Saluja Dec 13 '10 at 18:06
5 Answers
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
-
-
@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

Mikkel Lund
- 23
- 4
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