All other procedures and functions written to manage the array play basically on few main points:
- array's length (to be got or to be set);
- array's scanning (typically through loops);
- dereference.
Look at the code below:
procedure TForm1.deleteEmployee(id:integer); var i,k,imax,deletepoint :integer; begin imax:=self.findNumberOfEmployees-1; deletepoint:=0; for i:=0 to imax do begin if self.EmployeeArray[i].id = id then begin deletepoint:=i; if deletepoint < imax then begin for k:=deletepoint+1 to imax do begin self.EmployeeArray[k-1]:=self.EmployeeArray[k]; end; SetLength(self.EmployeeArray, imax); //deletepoint = imax end else begin //deletepoint = imax SetLength(self.EmployeeArray, imax); end; break; end; end; end;
The deleteEmployee procedure receives an integer, the ID of employee to "fire".
By scanning with for loop through all the array, it looks for the corresponding ID; once found, it proceeds with deletion and if it isn't the last item then move each successive item a step before, so that the forth becomes the third, and so on.
Both in case ID is the last or not, the procedure sets the new length, one less than the previous (obviously).
Notice that after moving back items, the SetLenght automatically deletes the last array item (already copied into preceding position): consequence of this is that SetLength(MyArray, 0) clears MyArray.
On the other side we have the getEmployee function, that receives the ID integer, returning a pointer to the related item.
function TForm1.getEmployee(id:integer): pEmployee; var i,imax :integer; begin result:=nil; imax:=self.findNumberOfEmployees-1; for i:=0 to imax do begin if self.EmployeeArray[i].id = id then begin result:= @self.EmployeeArray[i]; break; end; end; end;
Here is important to look at result := @self.EmployeeArray[i]; !
It returns a pointer to TEmployee!