Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Maybe you don't need twice pointers in each structure? You have arrays for chapters, for paragraphs - no need to use twice pointers.</p> <p>Provided code is more likely to use arrays, not lists. So if you are trying to use lists - I mentioned them in the end of answer. Otherwise, it is simpler to fix it to use arrays and here is the first problem:</p> <pre><code>if (++(books-&gt;numChapters) &gt; 0) { /* here books are reallocated */ books = realloc(books, sizeof(struct chapter*)*books-&gt;numChapters); /* but here chapters which had not been reallocated are acessed */ books-&gt;chapters[books-&gt;numChapters - 1] = nextChapter; } </code></pre> <p>If you have a new chapter then why do you need to realloc books? Just realloc books->chapters:</p> <pre><code>if (++(books-&gt;numChapters) &gt; 0) { books-&gt;chapters = realloc(books-&gt;chapters, sizeof(struct chapter*)*books-&gt;numChapters); books-&gt;chapters[books-&gt;numChapters - 1] = nextChapter; } </code></pre> <p>And in the end the same issue:</p> <pre><code>/* books are reallocated, size is bad - reallocated to size of numChapters * (pointer size) */ books = realloc(books, sizeof(struct chapter*)*books-&gt;numChapters); /* perhaps access to non-allocated memory here */ books-&gt;chapters[books-&gt;numChapters] = (void*)0; </code></pre> <p>Should be:</p> <pre><code>books-&gt;chapters = realloc(books-&gt;chapters, sizeof(struct chapter)*books-&gt;numChapters); // books-&gt;chapters[books-&gt;numChapters] = (void*)0; </code></pre> <p>Assigning NULL to the last element is not needed, because chapters has size of numChapters and accessing element numChapters cause access to non-allocaed memory, crash.</p> <p>All the code above uses a conception of arrays, not linked lists.</p> <p>To switch it to linked list it is necessary to use structures like the following:</p> <pre><code>struct paragraph { struct paragraph *next; // &lt;&lt;-- this field is used to build // linked list of paragraphs char* lines; int numLines; }; struct chapter { struct chapter *next; // &lt;&lt;-- this field is used to build // linked list of chapters struct paragraph* paragraphs; int numParagraphs; }; struct book { struct chapter* chapters; int numChapters; }; </code></pre> <p>Sure, appropriate allocations and assignment of "next" pointers are required.</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