If I want to create a 2D array, with dimensions specified by user input, can’t I just do this sequentially in the main function? Once I have the dimensions by using scanf, I then create an array with those dimensions? From what I understood, malloc is supposed to be used when the space required is not known at runtime. I wouldn’t’ve known the space required at runtime but I didn’t have to allocate the memory dynamically, and it would work anyway, right? Perhaps I’m completely misunderstanding something.
Share
Generally there are three reaons to use dynamic allocation in C:
The size is not known until runtime (another alternative is VLA‘s, but that’s C99 and potentially dangerous, see reason 2).
The size is (most likely) too big for the stack, risking stack overflow.
The object needs to live on the heap giving it a longer life than “automatic” storage.