what is the point of dynamic allocation in c? (plus dont get triggered. please explain why im wrong)
[C] ELI5: Dynamic Memory Allocation
Malloc is a way to ask the computer for a piece of memory.
The reason you would need to use malloc is to allocate memory dynamically as you have determined.
Let's say I have a file that contains N lines, where N is an arbitrary number that changes every time I run my program.
My program goes through and creates a linked list, where each node contains a single line of the file.
Why a linked list over an array? Well, because you need to know how big of an array you have to allocate it at run time. With a linked list I can dynamically malloc memory for each node as I iterate over the lines in the file. It does not necessitate prior knowledge.
You COULD allocate a huge array and just assume that you'll never have more than that many lines, but that is inefficient.
It's not only useful for linked lists, obviously, but this is a good example of why you would need to use malloc.
This might be a good starting place to learn about it.
More on reddit.comDynamic Memory Allocation
Can anyone explain dynamic memory allocation for a beginner?
Videos
So lets say i do int x=5; so i create a variable of 4 bytes that stores a value of 5
then i do int *y= malloc(sizeof(int)); here i created a pointer that gave me a memory location in the RAM and i can do *y=5; to store 5 in it. What exactly is the benefit of using dynamic allocation here?
plus in case of strings how do i dynamically allocate just enough memory to store name of some guy in c without knowing it before hand how long the name is?
like char name[4]; means i have an array of 5 char out of which im supposed to use 4. But here i need to make sure name is of length 4 always.
but char *name = malloc(5*sizeof(char)); dynamically allocates the same memory but i still need to make sure length of name stays 4 plus one extra for the null.
how is this implemented to take values of any length?