Link to home
Start Free TrialLog in
Avatar of ramnars
ramnars

asked on

dynamic data inside a loop

I have a loop inside which I will be getting external data using some function call. That function call returns an integer value which is the data.
Inside that loop, I want to keep accumulating all these data and once the loop is over, i'd like to process that data seuqntially.

how do i implement this. I do not know how many results i will be getting back . so every thing has to be dynamic.
pointer to pointer? array of pointers? what do i use?

Thanks
R
Avatar of griessh
griessh
Flag of United States of America image

Hi ramnars,

Either
you create a buffer big enough to handle the maximum amount of data
or
you allocate memory ( malloc() ) for the new data, process it and then free it at the end.

======
Werner
Avatar of ramnars
ramnars

ASKER

Actuallly I want a container like thing. just like c++ vector.
It depends on the size and the probability of the length of the data.

If the size can vary in very large amounts,malloc() a memory of a certain size and realloc another batch, when the current one gets full,using realloc().

If the size doesnt vary largely,malloc a large length or define an array of  a large enough size.

For the first case,
int *arr;
arr=(int*)malloc(100*sizeof(int));//say you allocate space for 100 integers initially

Inside the loop,if you need to realloc.

arr=(int *)realloc(arr,200);//now arr has space for 200 integers.the second argument specifies the new size.
Avatar of ramnars

ASKER

ok. I want to process all the data only after the loop is over. So in ur example, I need to store arr into some other variabale and process that list later. Do I need to use a linked list? or is there any other option ?
No.You can use arr as the array to store the data.You just dynamically keep setting its size to accomodate the new elements.
ASKER CERTIFIED SOLUTION
Avatar of ankuratvb
ankuratvb
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ramnars

ASKER

got it. thanks