- #1
angelspikes
- 10
- 0
There are two ways I'm used to allocate memory dynamically.
int * array = malloc(10 * sizeof(int));
But this type of memory allocation, have a predefined size, which is not desirable.
I keep hearing about linked list and push & pop. I've reviewed them over and over again, and they just look like an awful mess, and they have so many drawbacks. Some of the "practical" examples for a linked list has shown to be like 40 pages long. Below is my own way of allocating dynamic memory using realloc. It's plain and simple. You start with an empty array, then add data when needed, and you can delete it when you don't need it anymore, or why bother, just replace it:
#include <stdlib.h>
#include <stdio.h>
struct IO
{
int myInput;
} *pointer;
int main ()
{
// Put the two lines below in a loop which will fill up the dynamic array
pointer = (struct IO *) realloc (pointer, n * sizeof(struct IO));
pointer[n].myInput = myInput;
free (pointer);
}
Now you tell me, which one of these do you prefer, and would you still suggest me using a linked list or push & pop?
int * array = malloc(10 * sizeof(int));
But this type of memory allocation, have a predefined size, which is not desirable.
I keep hearing about linked list and push & pop. I've reviewed them over and over again, and they just look like an awful mess, and they have so many drawbacks. Some of the "practical" examples for a linked list has shown to be like 40 pages long. Below is my own way of allocating dynamic memory using realloc. It's plain and simple. You start with an empty array, then add data when needed, and you can delete it when you don't need it anymore, or why bother, just replace it:
#include <stdlib.h>
#include <stdio.h>
struct IO
{
int myInput;
} *pointer;
int main ()
{
// Put the two lines below in a loop which will fill up the dynamic array
pointer = (struct IO *) realloc (pointer, n * sizeof(struct IO));
pointer[n].myInput = myInput;
free (pointer);
}
Now you tell me, which one of these do you prefer, and would you still suggest me using a linked list or push & pop?