In by-value method the array hosts records, but remember a main thing: composed data structures are abstraction in memory representation, so that if you declare a variable of every type, it still lives until you don't explicitly delete it.
Local variables, whose life cycle is limited inside its environment (a function or procedure execution), still remains in memory: simply your program abandons them definitively (so that your operating system knows it can use those memory locations).
So... in a strange way you always put addresses into array: management is the key of change!
In by-value approach array hosts labels of records, labels which mask the memory locations addresses: instead with by-pointer method array hosts labels of memory locations whose values are addresses (so pointers) of other locations with our final data.
The complex round here exposed is necessary to highlight the different abstraction level.
If you didn't lose yourself, let's come back to our array: we know we have pointers to records inside.
//I add employees on the end of EmployeeArray ONLY procedure TForm1.addEmployee(pEmp:pEmployee); var imax :integer; begin imax:=self.findNumberOfEmployees; SetLength(self.EmployeeArray, imax+1); self.EmployeeArray[imax] := pEmp; //copy by pointer end; ... procedure TForm1.ButtonAddClick(Sender: TObject); var pEmpTemp:pEmployee; begin //create a new temp employee, with dynamical memory allocation //it reserves new memory space - if required - during execution new(pEmpTemp); pEmpTemp^.Id := self.findNextFreeId; // pEmpTemp^ DEREFERENCE pEmpTemp^.Name := EditNameNew.Text; pEmpTemp^.Surname := EditSurnameNew.Text; self.addEmployee(pEmpTemp); showmessage('Employee with this info : ' + self.printEmployeeWithId(pEmpTemp^.Id) + ' added into array.'); end;
Code above shows two related procedures:
- first, to add employee into array;
- second, to manage the add event and then to call first procedure.
By starting from last one, we imagine to click the Add button with all data: it creates a new pEmployee (pointer), which to pass values by dereference to.
After that, first procedure is called, with pointer as parameter which simply is stored into array.