Dynamic Multi-dimensional Arrays
About
Let's make a 2D array with the number of rows and columns unknown at compile time.
We'll first create methods(functions for struct) and push the rows
and cols
to stack area.
And then in the init function newMyArray
, we'll use malloc
from stdlib
to allocate space for arr
in MyArray
and the pointer to MyArray
itself, and return the pointer.
After printing its content, we'll free the memory with free
from stdlib
.
Note
Note that:
struct
's must appear before they're used.You can access the content that's pointed by elements in structs and unions using arrow operator
->
.Always
free
memory after dealing with the memory allocated usingmalloc
.The idiomatic way to create methods for a struct in C is, just passing the struct or the pointer to it to the function that needs the struct.
Example
References
Last updated