Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For a basic example, allocate the <code>teachers</code> array of a <code>Lesson</code> object like this:</p> <pre><code>Lesson lesson; lesson.numberOfTeachers = 10; lesson.teachers = malloc(lesson.numberOfTeachers * sizeof(*lesson.teachers)); </code></pre> <p>And to deallocate:</p> <pre><code>free(lesson.teachers); </code></pre> <p>But you'll probably need to allocate the <code>Lesson</code> objects dynamically too.</p> <pre><code>Lessons lessons; lessons.numberOfLessons = 5; lessons.arr = malloc(lessons.numberOfLessons * sizeof(*lessons.arr)); </code></pre> <p>And then you'll populate in a loop:</p> <pre><code>for (size_t i=0; i&lt;lessons.numberOfLessons; i++) { Lesson *lesson = malloc(sizeof(*lesson)); lesson-&gt;numberOfTeachers = 10; lesson-&gt;teachers = malloc(lesson.numberOfTeachers * sizeof(*lesson.teachers)); lessons.arr[i] = lesson; } </code></pre> <p>And to deallocate:</p> <pre><code>for (size_t i=0; i&lt;lessons.numberOfLessons; i++) { free(lessons.arr[i]); } free(lessons.arr); </code></pre> <p>You'll also want to populate the rest of the fields, but I'll concentrate on the allocation and leave that to you.</p> <p>In real code you'll want to check the return values of your calls to <code>malloc</code> for errors, and respond accordingly.</p> <p>Reallocation is a little more tricky. Suppose that you want to change the length of the <code>teachers</code> array in a <code>Lesson</code> object. At this point I think you need to start wrapping things up in functions.</p> <pre><code>void SetTeacherCount(Lesson *lesson, int count) { Teacher* newTeachers = realloc(lesson-&gt;teachers, count*sizeof(*lesson-&gt;teachers)); if (newTeachers == NULL) { // handle error } lesson-&gt;teachers = newTeachers; } </code></pre> <p>This gets more tricky when you are reallocating an array that contains elements that also have dynamic memory allocated. You need to make sure that you <code>free</code> any such nested dynamically allocated memory before you reallocate the parent array.</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