Satender346
Satender346

Reputation: 352

how to allocate dynamic memory to an array when number of element is unknown in C

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

Upvotes: 1

Views: 900

Answers (2)

Prinz Km
Prinz Km

Reputation: 323

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.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182753

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.

Upvotes: 5

Related Questions