Note that there are some explanatory texts on larger screens.

plurals
  1. POC - realloc causes an issue with structure
    text
    copied!<p>First of all, my appology that the code I post below is a bit ambiguous, since I have to simplify it in a way that readers can understand (the original code is quite complicated).</p> <p>In the code below:</p> <ol> <li>There is a list of 10 items.</li> <li>Each item has a list of info about it.</li> <li>Each info has a list of name.</li> </ol> <p>So I'm trying to populate the list of items, but I failed at reallocate the memory on line that I marked "<code>&lt;&lt;&lt;&lt;</code>". There is no compiling error, but when I print all the items's names out, it doesn't print any of those. I did some debugging on it and I'm pretty sure that the line "<code>&lt;&lt;&lt;&lt;</code>" causes an error, but I don't know why.</p> <pre><code>typedef struct { char *name; } NAME; typedef struct { int id; int nNames; NAME *names; } INFO; typedef struct { INFO *info; } ITEM; void *buildListInfo(LIST *list) { if (list != NULL) { list-&gt;nNames++; list-&gt;names = realloc(list-&gt;names, sizeof(INFO) * list-&gt;nNames++); // &lt;&lt;&lt;&lt; list-&gt;names[list-&gt;nNames-1].name = "example"; // index 0 first } return list; } int main() { int itemSize = 10; ITEM *items = malloc(sizeof(ITEM)*itemSize); for (int i = 0; i &lt; ind-&gt;nTerms; i++) { items[i].info = malloc(sizeof(INFO)); } /* construct an array that holds the number of lists that an item has */ int num[itemSize]; for (int i = 0; i &lt; itemSize; i++) { num[i] = 0; } /* build all items, each item has a list that contains its info (many) */ while (&lt;some_finite_condition&gt;) for (int i = 0; i &lt; itemSize; i++) { items[i].info[num[i]] = *buildList(&amp;(items[i].info[list[i]])); num[i]++; } } } </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