How do you exactly do dynamic memory allocation?
Go to solution
Solved by dcgreen2k,
1 minute ago, Gat Pelsinger said:But my question is though, that how does it let us treat it as an array? We never defined it as an array.
It lets us treat it as an array because an array is just a contiguous block of memory. Malloc gives you a contiguous block of memory with a pointer to the very start of it.
On top of that, did you know that the [] arrays use is just syntax sugar? The square brackets are a short form of doing something called pointer arithmetic, which is how your computer actually works with arrays. Here's what I mean:
#include <stdio.h> #include <stdlib.h> int main() { // Allocate memory that can hold an array of 10 ints int* array = malloc(sizeof(int) * 10); // Fill up the memory with values from 0 to 9 for (int i = 0; i < 10; i++) { array[i] = i; } // Get the value at index 5 with regular array syntax int value_regular = array[5]; printf("%d\n", value_regular); // That array syntax actually expands to this pointer arithmetic int value_arith = *(array + 5); printf("%d\n", value_arith); // That expansion is also why we can do this weird thing int value_weird = 5[array]; printf("%d\n", value_weird); // Don't forget to free the memory free(array); return 0; }
In short, arrays are just something programming languages give us to make working with blocks of memory easier.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now