Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It looks like you're basically implementing a dynamic Matrix object here. You want something like:</p> <pre><code>typedef struct _object{ int rowsAmount; int columsAmount; int* matrix; int** rows; } object; object* newObject(int ra, int ca){ object* o = malloc(sizeof(object)); o-&gt;rowsAmount = ra; o-&gt;columsAmount = ca; o-&gt;matrix = malloc(ra * ca * sizeof(int)); o-&gt;rows = malloc(ra * sizeof(int*)); for (size_t i = 0; i != ra; ++i) o-&gt;rows[i] = o-&gt;matrix + (i * ca); return o; } </code></pre> <p>You should also create a destructor function <code>destroyObject</code>, which similarly <code>free</code>s all the memory allocated for <code>o</code> and <code>o-&gt;matrix</code>.</p> <p><em><strong>Edit</em></strong>:</p> <p>However, your comment that:</p> <blockquote> <p>"I'm just trying to learn c, this is only about the setting the size. I just happened to try it with 2 arrays"</p> </blockquote> <p>...makes this question somewhat confusing, because it indicates you are not, in fact, trying to create a matrix (2D array) despite your use of "row"/"column" terminology here, but that you simply want to understand how to dynamically allocate arrays in C.</p> <p>If that's the case, an array in C is dynamically allocated using a pointer variable and <code>malloc</code>:</p> <pre><code>size_t array_size = 10; /* can be provided by user input */ int* array = malloc(sizeof(int) * array_size); </code></pre> <p>And then later, the dynamically-allocated array must be freed once you are finished working with it:</p> <pre><code>free(array); </code></pre>
 

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