Observer to review my C Interview response

WBahn

Joined Mar 31, 2012
32,894
I'm not sure what the best answer to the interviewer's last question should be.



I presented two answers, but you both mentioned they may not be fully relevant.

Could you please share what you think a relevant answer would be? Apologies for asking so directly.
So, I'll write this off-the-cuff as it I were just asked it in an interview.

Interviewer: But look at this code, the program doesn't know the size of n at compile time but still allocates, store the values. Why would we need dynamic memory if we can achieve this with static memory?

Me: Good point. I was a bit too cavalier with my prior answer. The newer C standards do allow you to define what are known as variable-length arrays as long as the size that is needed is known at runtime at the point where the memory for the array is allocated. So I was incorrect when I said that you needed to know the size of the array at compile time. However, we still have to deal with situations in which we don't know what the size of the array needs to be at the time that we need to allocate the memory for it, such as when data is being streamed to us from some source and we are looking for some kind of sentinel value to tell us we are done. For those situations, we can dynamically allocat memory as it is needed, perhaps using a linked list data structure. Once we have all the data, and if it makes sense to do so, we can then allocate a variable length array to hold the data and copy it over.

Another situation where we might want to dynamically allocate memory is when we don't want to have the data on the stack, usually because it's too large. If we want our variable to be automatic, it will usually be stored on the stack. So we can allocate an automatic variable that is a pointer and then dynamically allocate the actual memory for the array from the heap.
 
Top