Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In object oriented programming languages, an array of objects is really just an array of pointers to the objects. So if a pointer takes 4 bytes, and an object takes 5, an array of 10 objects will actually be 4*10 bytes long (plus overhead).</p> <pre><code>MyClass[] my_variable = new MyClass[10]; // this will allocate 10*pointersize bytes, plus overhead, you still need to allocate more space for the objects themselves </code></pre> <p>In C, an array of structures is an array of structures. If a structure takes 8 bytes, an array of 10 of them takes 80 bytes. You don't need to allocate even more space. It's already there.</p> <pre><code>struct data_t my_variable[10]; // this will allocate 10*sizeof(data_t) bytes </code></pre> <p>So the easy answer is:</p> <pre><code>int function2(struct Person *list, int *index) { char* nameInput; // User input code goes here ... // IMPORTANT: the user input code must allocate the space for nameInput // if it doesn't, then a copy of the buffer must be made // instead of the direct assignment below // the memory for this instance of the person was already created when the // array was created, so just save the values list[*index].name = nameInput; list[*index].age = ageInput; *index += 1; return 0; } </code></pre> <p>When your code executes this line:</p> <pre><code>list[(*index)++] = *prsn; </code></pre> <p>It is quite literally copying 8 bytes (on a 32 bit machine, sizeof(int) + sizeof(char*)), as I think you noticed something was up with your commment "// !Why use the dereferencing *prsn here?"</p> <p>The address to the memory allocated with malloc isn't being copied in that line, but the contents of the memory are. That's why it is a memory leak, the address is lost when the function exits because it was never put into the array.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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