3

I have a function that takes in a pointer to a series of char. I wish to copy 256 chars from that point, and place them in a string.

msg is not null-terminated.

The below code seems to give me some problem. Is there a correct 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;

4 Answers 4

13
SetString(myStr, msg, 256);
Sign up to request clarification or add additional context in comments.

4 Comments

I replaced the entire for loop with this single function. And it works perfectly.
Why do we not need to allocate buffer for myStr? Is it because SetString does it for you?
Yes: docwiki.embarcadero.com/VCL/en/System.SetString (the long string part is relevant in this case).
Length seems to be a bad parameter name since it's unclear if it's length in Bytes or Length in Char's (it's Chars btw).
3

Your code misses SetLength, the corrected version is:

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

The assignment can be done more efficiently as already answered.

Updated

SetLength allocates 256 characters + terminating 0 for myStr; without SetLength your code is an error: it writes to wild address and will finally result in access violation.

2 Comments

Why do you have to SetLength? Does it allocate 256 bytes of buffer for myStr?
@seveleven: Yes. Imagine you have myStr := 'test'. Then, of course, you cannot access myStr[7]. You have to set the length of the string - then you can set its characters.
2

If msg is null-terminated, as it should be, and the 256 characters you want to obtain are followed by the null character, simply do

myStr := msg;

If msg is longer than that, you could just do

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

In this case, a better method is

myStr := WideCharLenToString(msg, 256);

assuming you are using Delphi 2009 or later, in which the strings are Unicode.

1 Comment

If msg is not nulterminated there is no (standard) way to determine how long msg is. And thus also not how many characters to copy. In that case, you have to specify how to determine the length of msg.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.