How to convert char array with zero completion to string?

I have a function that takes a pointer to a char series. I want to copy 256 characters from this point and put them in a string.

msg does not end with zero.

The following code seems to give me some problem. Is there a proper way to do this?

Init( msg: PCHAR)
var
 myStr: String;
begin
 for i:= 1 to 256 do
 begin
  myStr[i] := msg[i-1]; 
 end;
end;
+3
source share
4 answers
SetString(myStr, msg, 256);
+13
source

Your code skips SetLength, fixed version:

Init( msg: PCHAR)
var
 myStr: String;
begin
 SetLength(myStr, 256);
 for i:= 1 to 256 do
 begin
  myStr[i] := msg[i-1]; 
 end;
end;

Appointment can be performed more efficiently, as already mentioned.

Update

SetLength allocates 256 characters + 0 termination for myStr; without SetLength your code is an error: it writes to wild address and, finally, leads to access violation.

+3
source

msg , , 256 , , ,

myStr := msg;

msg , ,

myStr := Copy(msg, 1, 256);

myStr := WideCharLenToString(msg, 256);

provided that you are using Delphi 2009 or newer, in which the strings are Unicode.

+2
source

myStr: = Copy (msg, 1, 256);

-1
source

Source: https://habr.com/ru/post/1770538/


All Articles