I know it could be done using malloc, but I do not know how to use it yet.
For example, I wanted the user to input several numbers using an infinite loop with a sentinel to put a stop into it (i.e. -1), but since I do not know yet how many he/she will input, I have to declare an array with no initial size, but I’m also aware that it won’t work like this int arr[]; at compile time since it has to have a definite number of elements.
Declaring it with an exaggerated size like int arr[1000]; would work but it feels dumb (and waste memory since it would allocate that 1000 integer bytes into the memory) and I would like to know a more elegant way to do this.
This can be done by using a pointer, and allocating memory on the heap using
malloc.Note that there is no way to later ask how big that memory block is. You have to keep track of the array size yourself.
That’s it. What follows is a more involved explanation of why this works 🙂
I don’t know how well you know C pointers, but array access in C (like
array[2]) is actually a shorthand for accessing memory via a pointer. To access the memory pointed to bydata, you write*data. This is known as dereferencing the pointer. Sincedatais of typeint *, then*datais of typeint. Now to an important piece of information:(data + 2)means "add the byte size of 2 ints to the adress pointed to bydata".An array in C is just a sequence of values in adjacent memory.
array[1]is just next toarray[0]. So when we allocate a big block of memory and want to use it as an array, we need an easy way of getting the direct adress to every element inside. Luckily, C lets us use the array notation on pointers as well.data[0]means the same thing as*(data+0), namely "access the memory pointed to bydata".data[2]means*(data+2), and accesses the thirdintin the memory block.