Compare Pointers in Virtual Pascal - pascal

I have to convert some procedures that used inline asm code in Virtual Pascal but don't know how to compare pointers in Virtual Pascal?
Here's example that causes a Operand types do not match operator on the While statement:
procedure ReverseBytes(var V; Size : Word);
{-Reverse the ordering of bytes from V[1] to V[Size]. Size must be >= 2.}
var
P1, P2 : ^Byte;
PT : Byte;
begin
P1 := #V;
P2 := P1;
Inc(P2, Size-1);
while (P1 < P2) do
begin
PT := P1^;
P1^ = P2^;
^P2 := PT;
Inc(P1);
Dec(P2);
end;
end;
How do you compare pointers (themselves - not what they point to) in Virtual Pascal?
P.S. I understand there are some flavors of Pascal (GNU Pascal for example) that support it just like C language (like I do above). But Virtual Pascal doesn't.
TIA!!

Related

Pascal - Incompatible type: Got "Array Of Extended", expected "QWord" / error

I am trying to sort an array of 100000 extended numbers using a quicksort algorithm, but I keep getting the following errors when calling the procedure:
source.pas(69,26) Error: Incompatible type for arg no. 1: Got "Array[1..100000] Of Extended", expected "QWord"
source.pas(69,36) Error: Incompatible type for arg no. 1: Got "Array[1..100000] Of Extended", expected "QWord"
program test;
type
TVector = array of double;
var
N,M,i,x:longint;
a,b,c,apod,af: Array[1..100000] of extended;
procedure QuickSort(var apod: TVector; iLo, iHi: Integer) ;
var Lo, Hi: Integer;
pivot,t: double;
begin
if (iHi-iLo) <= 0 then exit;
Lo := iLo;
Hi := iHi;
Pivot := apod[(Lo + Hi) div 2];
repeat
while A[Lo] < Pivot do Inc(Lo);
while A[Hi] > Pivot do Dec(Hi);
if Lo <= Hi then
begin
T := apod[Lo];
apod[Lo] := apod[Hi];
apod[Hi] := T;
Inc(Lo) ;
Dec(Hi) ;
end;
until Lo > Hi;
if Hi > iLo then QuickSort(apod, iLo, Hi) ;
if Lo < iHi then QuickSort(apod, Lo, iHi) ;
end;
begin
{a[i],b[i],c[i],af[i],N,M are initialiazed here}
apod[i]:=(a[i]-((a[i]*b[i])/3000)-((c[i]*a[i])/40));
end;
begin
QuickSort(apod, Lo(apod), Hi(apod)) ;
end;
end.
How can I fix this?
You have several syntactical errors in your code. I did not check if your quicksort is actually correct. You can debug that.
Array types
You are confusing several different things:
dynamic arrays (e.g. type array of double),
static arrays (e.g. type array[a..b] of double) and probably
open array parameters (parameter array of double).
Your parameter is a dynamic array type (TVector), but you pass a static array. These are not compatible.
To be able to pass a dynamic as well as a static array, you can use the mentioned open array parameters (note that they look like, but are not the same as dynamic arrays).
procedure QuickSort(var apod: array of Double; iLo, iHi: Integer);
More about open array parameters in an article of mine: Open array parameters and array of const.
Var (reference) parameters
But there is another problem: var parameters must have the exact type (or base type). No conversion will take place. So your a, b, c, apod and af parameters must contain Doubles too:
var
a, b, c, apod, af: array[1..100000] of Double;
Unbound blocks
Then the loose begin endblocks after the QuickSort function don't make sense. That is not Pascal. Rather do something like this in the main block (the last begin ... end. — note the final .):
begin
for i := Low(apod) to High(apod) do
apod[i] := (a[i] - ((a[i] * b[i]) / 3000) - ((c[i] * a[i]) / 40));
QuickSort(apod, Low(apod), High(apod));
end.
But note that the code above doesn't make a lot of sense. Probably all values in apod will be 0, since a, b, c, etc. are not initialized yet (so a[i] etc. are probably all 0).
I have no idea where you got that code, but you may want to try to understand it, before you start translating it to Pascal.
Lo and Hi
Note that you should use Low and High. Lo and Hi are something totally different: they get the low and high byte of a 16 bit word, respectively. Low and High get the bounds of arrays, sets and types.

Dynamic array in Turbo Pascal

I am working on my school project and I would like to use Dynamic (not static) array. I worked with ObjectPascal, so I am used to some syntax. But now I am programming in the old TurboPascal (I am using Turbo Pascal 7 for Windows).
It doesn't seem to know the ObjectPascal, so I thought, that you Turbo Pascal doesn't know dynamic arrays.
Could anyone tell me, if my theory is right or not? I tried to google, but I was not succesfull.
Basicly I am asking "how is it with dynamic arrays in Turbo Pascal 7" ?
Thank you for all reactions.
As MartynA says, there is no dynamic array type in Turbo Pascal. You need to manually allocate memory using pointers, and be careful if you use rangechecks.
Typically you define an array type
TYPE
TArrayT = array[0.. ((65535-spillbytes) div sizeof(T))-1] of T;
where spillbytes is a constant for a small deduction because you can't use the whole 64k, see what the compiler accepts. (Probably this deduction is for heapmanager structures inside the 64k block)
Then you define a pointer
PArrayT= ^TArrayT;
and a variable to it
var
P : PArrayT;
and you allocate nrelement elements using getmem;
getmem(P,SizeOf(T) * nrelements);
and optionally fill them with zero to initialize them:
fillchar(p^,SizeOf(T) * nrelements,#0);
You can access elements using
p^[index]
to free them, use freemem using the exact opposite of the getmem line.
freemem(P,Sizeof(T)*nrelements);
Which means you have to save the allocated number of elements somewhere. This was fixed/solved in Delphi and FPC.
Also keep in mind that you can't find bugs with rangechecking anymore.
If you want arrays larger than 64k, that is possible, but only with constraints, and it matters more which exact TP target (dos, dos-protected or Windows you use) I advise you to search for the online SWAG archive that has many examples. And of course I would recommend to go to FreePascal/Lazarus too where you can simply do:
var x : array of t;
begin
setlength(x,1000000);
and be done with it without additional lines and forget about all of this nonsense.
I'm using Turbo Pascal 5.5 and to create a dynamic array, perhaps the trick is to declare an array with zero dimension as follows:
dArray = array [0..0] of integer;
And then declare a pointer to that array:
pArray = ^dArray ;
And finally, create a pointer variable:
ArrayPtr : pArray;
You can now reference the pointer variable ArrayPtr as follows:
ArrayPtr^[i]; { The index 'i' is of type integer}
See the complete example below:
{
Title: dynarr.pas
A simple Pascal program demonstrating dynamic array.
Compiled and tested with Turbo Pascal 5.5.
}
program dynamic_array;
{Main Program starts here}
type
dArray = array [0..0] of integer;
pArray = ^dArray ;
var
i : integer;
ArrayPtr : pArray;
begin
for i := 0 to 9 do { In this case, array index starts at 0 instead of 1. }
ArrayPtr^[i] := i + 1;
writeln('The Dynamic Array now contains the following:');
writeln;
for i := 0 to 9 do
writeln(ArrayPtr^[i]);
end.
In this example, we have declared the array as:
array[0..0] of integer;
Therefore, the index starts at 0 and if we have n elements, the last element is at index n-1 which is similar to array indexing in C/C++.
Regular Pascal arrays start at 1 but for this case, it starts at 0.
unit Vector;
interface
const MaxVector = 8000;
// 64 k div SizeOf(float); number of float-values that fit in 64 K of stack
VectorError: boolean = False;
// toggle if error occurs. Calling routine can handle or abort
type
VectorStruc = record
Length: word;
Data: array [1..MaxVector] of float;
end;
VectorTyp = ^VectorStruc;
procedure CreateVector(var Vec: VectorTyp; Length: word; Value: float);
{ Generates a vector of length Length and sets all elements to Value }
procedure DestroyVector(var Vec: VectorTyp);
{ release memory occupied by vector }
procedure SetVectorElement(var Vec: VectorTyp; n: word; c: float);
function GetVectorElement(const Vec: VectorTyp; n: word): float;
implementation
var ch: char;
function WriteErrorMessage(Text: string): char;
begin
Write(Text);
Read(WriteErrorMessage);
VectorError := True; // toggle the error marker
end;
procedure CreateVector(var Vec: VectorTyp; Length: word; Value: float);
var
i: word;
begin
try
GetMem(Vec, Length * SizeOf(float) + SizeOf(word) + 6);
except
ch := WriteErrorMessage(' Not enough memory to create vector');
exit;
end;
Vec^.Length := Length;
for i := 1 to Length do
Vec^.Data[i] := Value;
end;
procedure DestroyVector(var Vec: VectorTyp);
var
x: word;
begin
x := Vec^.Length * SizeOf(float) + SizeOf(word) + 6;
FreeMem(Vec, x);
end;
function VectorLength(const Vec: VectorTyp): word;
begin
VectorLength := Vec^.Length;
end;
function GetVectorElement(const Vec: VectorTyp; n: word): float;
var
s1, s2: string;
begin
if (n <= VectorLength(Vec)) then
GetVectorElement := Vec^.Data[n]
else
begin
Str(n: 4, s1);
Str(VectorLength(Vec): 4, s2);
ch := WriteErrorMessage(' Attempt to read non-existent vector element No ' +
s1 + ' of ' + s2);
end;
end;
procedure SetVectorElement(var Vec: VectorTyp; n: word; C: float);
begin
if (n <= VectorLength(Vec)) then
Vec^.Data[n] := C
else
ch := WriteErrorMessage(' Attempt to write to non-existent vector element');
end;
end.
As long as your data fit on the stack, i.e., are smaller than 64 kB, the task is relatively simple. The only thing I don't know is where the 6 bit of extra size go, they are required, however.

How to use a variable in an array?

I'm using PASCAL for a course i'm doing and i'm having trouble with an assignment, in my program i'm using 2 arrays that uses a variable from a user's input but when i go to run the program it comes up with, Error: Can't evaluate constant expression. The code for the array is:
Var
x : integer;
s : array[1..x] of real;
n : array[1..x] of string[30];
Here x is the user's input, is there a way for an array to go from 1 to x?
If x is a variable, that won't work indeed. The range of a so called static array must be a constant expression, i.e. it must be known at compile time.
So what you want won't work, as is.
In FreePascal, you can use dynamic arrays, though. Their lengths can be set and changed at runtime.
var
x: Integer;
s: array of Real;
n: array of string[30]; // why not just string?
and later:
x := someUserInput(); // pseudo code!
SetLength(s, x);
SetLength(n, x);
You should be aware of the fact that dynamic arrays are 0-based, so your indexes run from 0 up to x - 1. But for the limits of the array, you should rather use Low() and High() instead:
for q := Low(s) to High(s) do
// access s[q];
(Low() and High() are not the topic, but just know they can also be used for static arrays, and that they return the actual array bounds -- I always use High and Low for this)
Here is not so simple as using managed types like dynamic arrays suggested by #RudyVelthuis but more funny solution providing some comprehension
about how it works internally :)
program dynarr;
{$mode objfpc}{$H+}
type
TArrayReal = array[1..High(Integer)] of Real;
TArrayString30 = array[1..High(Integer)] of string[30];
PArrayReal = ^TArrayReal;
PArrayString30 = ^TArrayString30;
var
i: Integer;
x: Integer;
s: PArrayReal;
n: PArrayString30;
begin
Write('Count: '); Readln(x);
// Allocate memory for the actual count of the elements
s := GetMem(SizeOf(Real) * x);
n := GetMem(SizeOf(string[30]) * x);
try
for i := 1 to x do
begin
Write('Row ', i:3, ': '); Readln(s^[i], n^[i]);
end;
Writeln('Your input was:');
for i := 1 to x do
Writeln('Row ', i:3, ': ', s^[i]:10:3, n^[i]: 20);
finally
// Do not forget to release allocated memory
FreeMem(s);
FreeMem(n);
end;
end.

How do i compare 3 numbers in Pascal?

i'm a newbie
and I need how to compare 3 numbers in Pascal.
Here is what I tried so far
BEGIN
max:=A;
IF B>A THEN max:= B;
IF C>B THEN max:= C;
END;
but when I choose, for example, A = 5 , B=2 , C=4, the output is 4, but it should be 5. Where is the problem?
I want at the end writeln('The Large Number is ',max);
You could do this (you should be comparing with max)
BEGIN
max:=A;
IF B>max THEN max:= B;
IF C>max THEN max:= C;
END;
You must compare with max instead of A or B.
Changing your code in a easy way:
BEGIN
max := A;
IF B > max
THEN
max := B;
IF C > max
THEN
max := C;
END;
Or, in a somewhat recent Pascal, like Delphi or Free Pascal, using the max function from the MATH unit.
result:=max(a,max(b,c));
Using the Max Function of Pascal
PROGRAM MaxProgram;
USES math;
VAR
num1,num2,num3,maxNum : INTEGER;
BEGIN
(* Receive the Values *)
WRITELN('Enter First Number');
READLN(num1);
WRITELN('Enter Second Number');
READLN(num2);
WRITELN('Enter Third Number');
READLN(num3);
(* Using the Max Function *)
maxNum := max(num1,max(num2,num3));
(* Display Result *)
writeln('The Highest number is ', MAXNUM);
END.

Obtaining the complex roots of a 2nd degree polynomial in pascal

I have to code a program in pascal that, given the three coefficients of a polynomial(ax²+bx+c), outputs its roots.
Here's what I have right now:
program poly;
type
polynomial = record
a, b, c : real;
end;
procedure readPolynomial (var p : polynomial);
begin
writeln ('Input 1st coefficient: ');
readln (p.a);
writeln ('Input 2nd coefficient: ');
readln (p.b);
writeln ('Input 3rd coefficient: ');
readln (p.c);
end;
function square (x : real) : real;
begin
square := x * x;
end;
procedure roots (p : polynomial; var rP, rN : real);
begin
rP := (-p.b + (sqrt((square(p.b)) - (4 * p.a * p.c)))) / (2 * p.a);
rN := (-p.b - (sqrt((square(p.b)) - (4 * p.a * p.c)))) / (2 * p.a);
writeln('The roots are: ', rP:0:3, ' y ' ,rN:0:3);
end;
var
myPolynomial : polynomial;
r1, r2 : real;
begin
writeln ('Enter the coefficients: ');
readPolynomial (myPolynomial);
roots (myPolynomial, r1, r2);
end.
It works fine for real roots but I don't know how to make it work with complex numbers.
I am assuming your coefficients are real numbers (they user can't enter complex numbers as coefficients). That would add a whole new level of complexity (no pun intended) to the problem.
You need to check the discriminant ((square(p.b)) - (4 * p.a * p.c)) to see if it's less than 0. Currently, your code just does, sqrt((square(p.b)) - (4 * p.a * p.c)) but you aren't checking if you are taking the square root of a negative number (which you can't do using the Pascal sqrt library function).
If the discriminant is negative, then you have a complex root and you can separate the real and imaginary parts as you wish in your program. It's basic quadratic formula.
For example:
procedure roots (p : polynomial; var rP, rN : real);
var disc: real;
begin
disc := square(p.b) - 4*p.a*p.c;
if disc >= 0 then begin
rP := (-p.b + sqrt(disc)) / (2 * p.a);
rN := (-p.b - sqrt(disc)) / (2 * p.a);
writeln('The roots are: ', rP:0:3, ' y ' ,rN:0:3);
end
else begin
// Roots are:
// -p.b/(2*p.a) + (sqrt(-disc)/(2*p.a))i
// -p.b/(2*p.a) - (sqrt(-disc)/(2*p.a))i
end
end;
Here you use the fact that sqrt(x) if x is negative would be, (sqrt(-x))i where i is sqrt(-1). Note that you could also split out the disc = 0 case to avoid repeating a double root.
Since your roots function prints out the results and your main program doesn't use the returned arguments rN and rP, it's not clear to me if you need to pass back the roots at all. But if want to pass the roots back as arguments (the way you have your function currently designed), I'll leave that as an exercise. You just have to decide on a representation for complex roots. One way is to use the Complex number type for the results (if your compiler library supports them), and when the results are real, the imaginary parts will just be zero. Alternatively, if you need to create your own, just make a type which is a record consisting of a real and imaginary part.
type complex = record
re: real;
im: real;
end;

Resources