To do this, we will be using a function called malloc() (memory allocation)
The syntax for malloc is as follows:
This may seem like a lot at first, but I'll break it down a bit starting from the right:
sizeof(type) will return the number of bytes which malloc will allocate to your program. For example, sizeof(char) will return 1 byte. Instead of using sizeof(), you could always just enter a number, but that's really bad practice, so I don't recommend it.
When you run malloc, it goes and asks the operating system "Can I get this much memory for my program?" and in general, it will return unspecified memory. This means that we have to cast it using (type*) because we know what this memory is being used for, but malloc() does not!
So now that I've explained the basics of malloc(), I'll give some examples:
p = malloc((int*)sizeof(int));
See, we are starting off with a pointer to an integer and we are setting it equal to the memory allocated by malloc(). Useful isn't it?
This is great, but there are even more applications. Take a look at this code:
p = malloc(int*)10*sizeof(int));
Have you caught on? Basically, malloc() went and asked the operating system "Can I get 10*sizeof(int) bytes to use?". We have gotten to enough memory for 10 integers which are all right beside each other in memory. What does this mean? We have dynamically created an array of integers. The multiplier can also be a variable. For example:
p = malloc(int*)x*sizeof(int));
There we go! An array of 42 integers. This can also be applied so that the user is asked to enter the size of the array and then an array of that size will be created.
I hope this first lesson has been informative! Keep on coding and be creative!