tags:

views:

121

answers:

4

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;
+2  A: 

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.

Andreas Rejbrand
msg is not null-terminated..
seveleven
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.
Marco van de Voort
A: 

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

jasonpenny
+3  A: 

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.

Serg
These code works perfectly
seveleven
Why do you have to SetLength? Does it allocate 256 bytes of buffer for myStr?
seveleven
@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.
Andreas Rejbrand
+11  A: 
SetString(myStr, msg, 256);
TOndrej
Why was this down-voted? It works perfectly.
Andreas Rejbrand
+1 I was just typing the same answer :)
The_Fox
I replaced the entire for loop with this single function. And it works perfectly.
seveleven
Why do we not need to allocate buffer for myStr? Is it because SetString does it for you?
seveleven
Yes: http://docwiki.embarcadero.com/VCL/en/System.SetString (the long string part is relevant in this case).
TOndrej
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).
Remko