D
D
dmitri_0012016-03-01 08:05:38
Pascal
dmitri_001, 2016-03-01 08:05:38

How to pass an array to a procedure?

Good afternoon. I am writing a program in PascalABC that should compare arrays, the action itself needs to be done through procedures. I'm trying to pass arrays to a procedure, but I'm getting an error.

Program1.pas(33) : Нельзя преобразовать тип array [0..3] of integer к array of integer

The code looks like this:
procedure test(a,b: array of integer);
actually the arrays themselves that I pass are called as
a: array [0..3] of integer;
How to proceed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Fedoryan, 2016-03-01
@dmitri_001

Installed Pascal ABC.net (version 3.1, build 1179 dated February 29, 2016)
As the help says :
When passing a static array to a subroutine by value, the contents of the array - the actual parameter - are also copied into the array - the formal parameter:

procedure p(a: Arr); // передавать статический массив по значению - плохо!
...
p(a1);

This is extremely wasteful, so static arrays are recommended to be passed by reference. If the array does not change inside the subroutine, then it should be passed as a reference to a constant (const), if it changes, as a reference to a variable:
type Arr = array [2..10] of integer;

procedure Squares(var a: Arr);
begin
  for var i:= Low(a) to High(a) do
    a[i] := Sqr(a[i]);
end;

procedure PrintArray(const a: Arr);
begin
  for var i:= Low(a) to High(a) do
    Print(a[i])
end;

var a: Arr := (1,3,5,7,9,2,4,6,8); 

begin
  Squares(a);
  PrintArray(a);
end.

To access the lower and upper bounds of the dimension of a one-dimensional array, the and functions are Lowused High.
Here is the working code:
Program arrays;
type
  tArray = array [0..3] of integer;

var
  a, b: tArray;
  i: integer;

procedure FirstProcedure(a, b: tArray); 
begin
  writeLn(a);
end;

begin
  for i := Low(a) to High(a) do
    begin
      writeLn('WHAT IS A' + i + '?');
      readLn(a[i]);
    end;
    
  for i := Low(b) to High(b) do
    begin
      writeLn('WHAT IS B' + i + '?');
      readLn(b[i]);
    end;

  FirstProcedure(a,b);
end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question