Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An array of pointers that point to the same array

Tags:

delphi

pascal

I've read a piece of Delphi code like this :

sample1  = ARRAY[1..80] OF INTEGER; 
psample =^sample1;

VAR
  function :ARRAY[1..70] OF psample;

From my understanding, the programmer is trying to declare an array that contains 70 pointers and each pointer points to a sample1 array.

So when I write :

function[1]^[1] := 5;
function[1]^[2] := 10;

then :

function[n]^[1] := 5 
function[n]^[2] := 10; ( n = 2 to 70)

Is that correct ?

like image 582
Jay Dao Avatar asked Feb 02 '12 21:02

Jay Dao


2 Answers

Your code sample is lacking some information since you do not say how function is defined. This means that you cannot draw the conclusions that you attempt to draw.

Of course, since function is a reserved word in Pascal, that code could never even compile. I will assume now that the variable is called f.

Consider the following definitions:

type
  sample1 = array [1..80] of integer; 
  psample = ^sample1;

var
  f : array [1..70] of psample;

Here, sample1 and psample are types. sample1 is type describing an array of 80 integers. psample is a pointer to a sample1.

Next a variable named f is defined. It is an array of 70 psamples.

Now, before you can even consider what happens when you write f[1]^[1], we need to assign some values to the elements of f.

Suppose we did it like this:

var
  sample: sample1;
...
for i := 1 to 70 do
  f[i] := @sample;

Now it would be true that f[i]^[k] refers to the same integer as f[j]^[k] for all valid i and j. So when you write f[1]^[1] := 42 you are also assigning that value to f[2]^[1], f[3]^[1] and so on.

On the other hand you could do it like this:

var
  samples: array [1..70] of sample1;
...
for i := 1 to 70 do
  f[i] := @samples[i];

Now each f[i] pointer points to a distinct array in memory. In this case assigning f[1]^[1] := 42 does not modify the value of f[2]^[1] or any of the other values.

like image 55
David Heffernan Avatar answered Sep 29 '22 06:09

David Heffernan


That is correct. You have 70 pointers, each pointing to an array of 80 integers.

like image 35
500 - Internal Server Error Avatar answered Sep 29 '22 06:09

500 - Internal Server Error