Hairy Pixels via fpc-pascal said on Thu, 22 Jun 2023 20:23:13 +0700
Show quoted text 16 lines
I've forgotten entirely, what does subscripting a pointer do in
Pascal? p[0] returns 100 but after that garbage. Seems like a c-style
array which doesn't feel right in the language.
var
i: Integer;
p: PInteger;
begin
p := @i;
p^ := 100;
writeln(p[0]);
writeln(p[1]);
writeln(p[2]);
Regards,
Ryan Joseph
I don't do much with Pascal pointers, but it looks to me like you:
* Set p to the address of i
* Set the contents of p to 100
* Read the contents of p, which of course would be the value of i, 100
* Read the contents of p+1, which would be one integer width away on the stack, and has not been assigned to anything.
So what you report is exactly what I'd expect to happen.
If p were pointing to the first element of an array of integer that had been initialized, it would have worked the way you intended.
p[1] is undefined, but if I had to guess, the way most compilers seem to work, I'd say it would be one integer width of the value of p[0], which is the address of i. If my supposition is correct, by modifying the contents of p[1] and maybe some other elements of p, you could write some pretty interesting self-modifying code. But don't do that.
SteveT
Steve Litt
Autumn 2022 featured book: Thriving in Tough Times http://www.troubleshooters.com/bookstore/thrive.htm