I want to do the following but I get "Access violation" error.
type Bin = array of byte;
var s:string;
begin
s:='some string';
Bin(s)[3]:=ord('X');
caption:=s;
end;
Why this doesn't work ?
I want to do the following but I get "Access violation" error.
type Bin = array of byte;
var s:string;
begin
s:='some string';
Bin(s)[3]:=ord('X');
caption:=s;
end;
Why this doesn't work ?
This does not work because AnsiString
and a dynamic array of byte are incompatible types. Your cast is invalid and anything can happen.
As it turns out, your string is a literal. The compiler handles that by putting the string in read only memory. Hence the access violation when you go behind its back.
The solution is easy enough. Use the []
indexing operator on the string directly:
s[i] := ...;
When you do this, the compiler knows that the string is read-only, and copies it to writeable memory to allow you to modify it.
You say that you don't want to use ord()
and chr()
. I don't know why. They are the correct things to use and, it's not as if they even result in any code being emitted. They are intrinsics that turn into no-ops.
You state in a comment that you are coding an encryption algorithm. This then points up the fundamental flaw in your approach. Encryption algorithms operate on byte arrays. Don't feed text into an encryption code. Convert to a byte array using some well-defined text encoding. And then operate on byte arrays. And don't reinvent the wheel. Use an existing crypto library.