delphi modify pchar at runtime

267 Views Asked by At

I need to modify pchar string at runtime. Help me with this code:

var
  s:pChar;
begin
  s:='123123';
  s[0]:=#32; // SO HERE I HAVE EXCEPTION !!!
end.

Now i have exception in Delphi 7 ! My project is not using native pascal strings (no any windows.pas classes and others)

2

There are 2 best solutions below

9
On BEST ANSWER

You can:

procedure StrCopy(destination, source: PChar);
begin
  // Iterate source until you find #0
  // and copy all characters to destination.
  // Remember to allocate proper amount of memory
  // (length of source string and a null terminator)
  // for destination before StrCopy() call 
end;

var
  str: array[0..9] of Char;
begin
  StrCopy(str, '123123');
  s[0]:=#32;
end.
4
On

String literals are read only and cannot be modified. Hence the runtime error. You'll need to use a variable.

var
  S: array[0..6] of Char;
....
// Populate S with your own library function
S[0] := #32;

Since you aren't using the Delphi runtime library you'll need to come up with your own functions to populate character arrays. For instance, you can write your own StrLen, StrCopy etc. You'll want to make versions that are passed destination buffer lengths to ensure that you don't overrun said buffers.

Of course, not using the built in string type will be inconvenient. You might need to come up with something a little more powerful than ad hoc character arrays.