I have a list of records, at the starting I dont know the number of records. I need to read them into array. so is it advisable to read all record one by one & doing realloc one by one & go on increasing the array size as the element comes OR should I spend one pass in identifying the number of records & do malloc only once ? Which one will be be less computationally expensive ?
A realloc isn't really very expensive. But calling realloc for each element is a bit much.
If you take a look at the complexity, assuming realloc is O(N), you quickly conclude that adding a single byte is on average O(1), which is good.
It's perfectly safe to use realloc . It is the way to reallocate memory in a C program. However you should always check the return value for an error condition.
Use of realloc() realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes.
A realloc
isn't really very expensive. But calling realloc
for each element is a bit much. I suggest you do this:
Correctly guessing an adequate initial size also helps. So if 60% of your inputs are less than 100 records, start with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With