0
votes

Heloo guys... Once I try to run this code I am gettin an 'invalid pointer operation' error, what is the problem ? It is supposed to sort those names in that textfile into an alphabetical order (school project).

program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes;
var
  names : TextFile;
  count : integer=0;
  array : array of string;
  i : integer;

Procedure Load;
 begin
  Reset(names);
  SetLength(array, count - 1);
  for i := 1 to count do ReadLn(names, array[i]);
 end;

begin
  AssignFile(names, 'names.txt');
  Reset(names);
    While not EoF(names) do
      begin
      ReadLn(names);
      Inc(count);
      end;
   Load;
   for i := 1 to count do WriteLn(array[i]);
   ReadLn;
   CloseFile(names);
   Erase(names);
end.
1
I know its not set yet to sort those items in to an alphabetical order, cause i am not done yet...just have to solve this 'error problem' first. - Filip Sulik
If there are some 'syntax mistakes' its because I was writing it from my memory and not copy and pasting it (i also changed names of the variables , cause I had them named in my language(slovak))...I just wrote here something ,very similar, for you to get an idea about my problem - Filip Sulik
Why is your array count 0? You're essentially calling SetLength(Array, 0); - Jerry Dodge
it is not...you didnt read carefully - Filip Sulik
Got it, you're incrementing it. Still not the right way to do so. Eliminate this Count variable and read Length(array) instead. - Jerry Dodge

1 Answers

7
votes

Dynamic arrays are zero-based. You need to set the length to count and iterate from 0 to count-1.

SetLength(arr, count);
for i := 0 to count-1 do
  ReadLn(names, arr[i]);

Obviously all indexing needs to be changed to be 0-based.

I changed the name of the array to arr because array is a keyword.

Do not attempt to continue with 1-based indexing. Doing so will cause you endless headaches.

Also you should enable the range checking compiler option. Doing so will yield informative errors at runtime if you access an array out of bounds.