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

3
  • 1
    What you done there seems fine? Commented Sep 19, 2013 at 6:56
  • Why not search for previous posts that relevant to this question? Commented Sep 19, 2013 at 7:03
  • In C we don't cast the return from malloc, as a void * is assignment compatible with any object pointer. Commented Sep 19, 2013 at 7:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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.

3 Comments

i have to store record i.e userid from database which is unknown how much ids are there in database.
Can you elaborate your problem?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.