Reputation: 157
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.
Upvotes: 0
Views: 161
Reputation: 476990
Here's a archetypal example of the need for dynamic allocation: Making a dynamic container. Since you don't know the number of elements in advance, each element has to be allocated dynamically. Since you populate the container in a loop, each element must outlive the loop scope. This is the "zero-one-many" rule at its barest, and the "many" part of it immediately entails dynamic allocation:
int value;
node * my_list = NULL;
while (get_one_more_input(&value) == SUCCESS)
{
node * elem = malloc(sizeof(node));
elem->data = value;
elem->next = my_list;
my_list = elem;
}
The crux here is that the actual list node is only populated inside the loop which reads the input data, but clearly it must outlive that scope. Thus no automatic object can do, because it would only live to the end of the scope, and also no static element could do, because you cannot know the number of loop iterations beforehand. Dynamic lifetime and storage management is the only solution here, and that's what it is primarily intended for.
In C you will be doing a lot of this by hand, since dynamic data structures are at the very heart of computing. C++ makes a lot of this much easier and safer by wrapping all the dynamic management logic into hidden-away, reusable code that you never need to look at as a consumer (though it's still doing the exact same thing).
Upvotes: 0
Reputation: 272467
malloc
is generally used when the space requirements aren't known at compile-time, or when you need the object to persist beyond the scope that it was created in.
In C99 (unlike earlier versions of C), you can also define variable-length 1-dimensional arrays without using malloc
. But many people consider then evil, because there's no way to catch an out-of-memory condition.
But if you want something that acts like a multidimensional array (in the sense of being able to index it like x[i][j]
) where the dimensions aren't known until runtime, you will need to involve malloc
somewhere.
Upvotes: 0
Reputation: 117681
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.
Upvotes: 6