Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you are looking exists in C++, but not in C, I believe. In C++ you can define template functions for working with arrays of size, known at a compile time, and compiler takes care of the rest. In C, there are two approaches:</p> <ul> <li><p>Define the size explicitly<br> This is the case of functions like <code>memcpy</code>, where you specify number of elements </p> <pre><code>void process_array(int *data[], size_t max_x, size_t max_y) .... </code></pre></li> <li><p>Define the size using invalid number<br> This is the case of functions like <code>strlen</code> where data is terminated by certain value (<code>'\0'</code> here)<br> So if you want to have a function with matrix, but variable number of elements, you must define a way how to indicate that in the data.</p> <pre><code>#define ARRAY_TERM -1 void process_array(int *data[]) { size_t i, j; for (i = 0; data[i]; i++) { for (j = 0; data[i][j] != ARRAY_TERM; j++) { ... } } } ... </code></pre></li> </ul> <p>Hope you've got the idea. Not very convenient to use.</p> <p>There is another approach: define your own type. Yes, it is a viable option in many cases:</p> <pre><code>typedef struct array *array_t; struct array { size_t max_x, max_y; int *data; }; </code></pre> <p>Basic set of functions to work with it:</p> <pre><code>int array_init(array_t *a; size_t max_x, size_t max_y) { array_t res; res = malloc(sizeof(*res)); res-&gt;max_x = max_x; res-&gt;max_y = max_y; res-&gt;data = calloc(max_x * max_y, sizeof(int)); *a = res; return 0; } void array_destroy(array_t *a) { free((*a)-&gt;data); free(*a); } </code></pre> <p>And then you can define your additional functions for operation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload