>>31913Okay, so if you are writing a program in C, you can only have static sized arrays, i. e. the size of array is constant, so once it's set, it cannot be changed.
In C arrays are just fancy pointers to the consecutive data of the same type. So for example
int arr[] = {0, 78, 10};
creates an array of tree members, indexed from 0 to 2, and stores in memory (in .data segment particularly because it's a global variable)
The size of array can't be changed because it may AND WILL overwrite the variables that come after it.
In memory, this array looks something like this:
| 00 00 00 00 | 00 00 04 0E | 00 00 00 0A |
when you reference array like this
int x = arr[2];
it references data located at address which is stored at array (arr[0]) + sizeof(int) * 2
m'kay?
Now, how do we do dynamic sized arrays in C? Well, linked lists are helpful.
They are implement as structures, a composite data type:
struct LinkedList {
int value;
struct LinkedList *next;
}
This way we can have an array where data is not consecutive but referenced from the previous element, which means we can have as many elements as we want (the pointer of the last element should be NULL btw)
struct LinkedList *ll;
ll->value = 0;
ll->next = (struct LinkedList *)malloc(sizeof(struct LinkedList));
ll->value = 78;
ll->next->next = (struct LinkedList *)malloc(sizeof(struct LinkedList));
ll->value = 10;
ll->next->next->next = NULL;
(this is a plain way to do it, we can create functions which will abstract this code away so we can reference element by index and shi)
But this comes at a cost, because malloc is an expensive memory hogging bitch that will slow your program down by 0.0000000000000000000000001 nanoseconds on modern machines.