Recent

Author Topic: Passing an array to a procedure using var problem  (Read 10529 times)

undermanager999

  • Newbie
  • Posts: 3
Passing an array to a procedure using var problem
« on: March 12, 2012, 08:32:57 pm »
He all

I'm looking at very simple examples of parameter passing, using an array. When I pass the array rolls to the procedure initArray, and watch the elements get updated, something strange happens! When Values[1] becomes 3, Rolls[1] stays at zero and Rolls[2] becomes 3 instead. The two arrays seem out of sink by 1 as each element is updated. I've clearly done something wrong here. Could anyone point out the error of my ways, please?


program lookatarrays;

uses
 sysutils, crt;

const
  maxValue = 4;

var
  rolls :array [1..maxValue] of Integer;

procedure initArray(var values:array of integer;maximum:integer);

var
  counter : integer;

begin
     for counter := 1 to maximum do
     begin
          values[counter]:= 3;
     end;
end;

procedure writeArray(values:array of integer;maximum:integer);

var
  counter : integer;

begin
     for counter := 1 to maximum do
     begin
          writeln(values[counter]);
     end;
end;


begin

     initArray(rolls,maxValue);
     {writeArray(rolls,maxValue);}
     readln();
end.                             

ludob

  • Hero Member
  • *****
  • Posts: 1173
Re: Passing an array to a procedure using var problem
« Reply #1 on: March 12, 2012, 08:49:27 pm »
Code: [Select]
var values:array of integer;This is an open array which is always zero based. Its first element is values[0].

Code: [Select]
rolls :array [1..maxValue] of Integer;The first element is rolls[1]

So in procedure initArray,  rolls[1] = values[0]

You really shouldn't use such code. Do something like this
Code: [Select]
type
  TRollsarray=array [1..maxValue] of Integer;

var
  rolls:TRollsarray;

procedure initArray(var values:TRollsarray;maximum:integer);

No confusion possible.

undermanager999

  • Newbie
  • Posts: 3
Re: Passing an array to a procedure using var problem
« Reply #2 on: March 12, 2012, 10:34:36 pm »
A ha!

Thanks. :D

 

TinyPortal © 2005-2018