What are the advantages to it?
There are many differences between these, but one of the biggest is that the stack is usually limited to 1MB or 8MB. So if you try to declare an array of that size, the program will probably crash. With dynamic memory, it's not strange to allocate hundreds of MB or more.
Another big difference is that you can return pointers to dynamically allocated memory. That won't work with arrays.
// Dummy init function
void init(int * arr, size_t size)
{
for(int i=0; i<size; i++) arr[i] = i;
}
// Will compile, but the program will behave strange. Accessing a variable
// after it has gone out of scope causes undefined behavior.
int * returnArray()
{
int arr[10];
init(arr, 10);
return arr;
}
// Works perfectly;
int * returnMallocatedArray()
{
int * arr = malloc(10*sizeof(*arr));
init(arr, 10);
return arr;
}
How would I handle this matrix?
Just as a regular array. You can access the element (x,y) with something like mat[x+y*rows]
or whatever suits your need best. Just remember though, that as far as the compiler and runtime environment is concerned, the only thing that mat
is, is a pointer to a chunk of memory. It's up to you to do the mapping. Doing something like mat[x*cols+y]
would also work, as long as you don't mix them.