1

How to allocate dynamic memory to an array where size or number of element is unknown

int *p = (int*)malloc(i*sizeof(int)); here i also dynamic mean i may be 1 or 1000 we don't know so how to allocate size thanks

Satender346
  • 352
  • 1
  • 3
  • 15

2 Answers2

5

Start by allocating space for, say, 10 elements. If it grows past 10, then use realloc to grow the allocation to 20. If grows past 20, grow it to 40, and so on. Keep an 'alloc_size' variable and a 'count' variable. Before you add a new element, check if count == alloc_size, and if so, realloc.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Care needs to be taken to ensure that an obsolete pointer is not used somewhere else in your app after your pointer has been updated with realloc. One way to do that would be to pass a pointer to your pointer, instead of the pointer itself: &p instead of p. – Tarik Sep 19 '13 at 07:03
  • I think this answer would benefit from some discussion about how to decide how much memory to allocate, mentioning the golden ratio etc.. In your example you hint at a growth factor of '2' but you don't explain why. – Frerich Raabe Sep 19 '13 at 07:04
0

you set a single variable of array type. say ch, get it from user, use a pointer to implement array, if ch!='\n' realloc pointer repeat getting input; thats it.

Prinz Km
  • 323
  • 1
  • 12
  • i have to store record i.e userid from database which is unknown how much ids are there in database. – Satender346 Sep 19 '13 at 07:05
  • Can you elaborate your problem? – Prinz Km Sep 19 '13 at 07:08
  • i have to fatch some information from database suppose userid to view and analysis where how much userid are there database is unknown no of user id my be anythinng mean 1,2 or 1000 or 10000 how to store in in array – Satender346 Sep 19 '13 at 07:15