Home > Back-end >  Sorry to ask a very basic question, I have been used, pchar how to do?
Sorry to ask a very basic question, I have been used, pchar how to do?

Time:09-18

 
Procedure TForm2. Button10Click (Sender: TObject);
Var
C, c1: PChar;
The begin
GetMem (c, 5);
C1:='11.2';
Move (c1, c, 4);
ShowMessage (c);
FreeMem (c);
end;


Why does the code freemem error? If I applied for memory for pchar variables, how to write the content in it? If don't have to getmem to also can be used directly as if c1, copies the contents of c1 to c in the move, why freemem error?

CodePudding user response:

 
http://blog.csdn.net/tjb_1216/article/details/4627346
Procedure TForm1. Button1Click (Sender: TObject);
Var
C, c1: PChar;
The begin
GetMem (c, 5);
FillChar (c ^, # 5, 0).
C1:='11.2';
Move (c1 ^, c ^ 4);
ShowMessage (c);
FreeMem (c);
end;

CodePudding user response:

reference 1st floor wdonghai response:
 
http://blog.csdn.net/tjb_1216/article/details/4627346
Procedure TForm1. Button1Click (Sender: TObject);
Var
C, c1: PChar;
The begin
GetMem (c, 5);
FillChar (c ^, # 5, 0).
C1:='11.2';
Move (c1 ^, c ^ 4);
ShowMessage (c);
FreeMem (c);
end;


Thank you, excuse me, Move (c1, c, 4); Why an error?

CodePudding user response:

Pchar, can only use move, strcopy functions like operation? If there is a pchar, length is 10, I want to change to 5 characters, how to write?

CodePudding user response:

I know the
1, Move (c1, c, 4); Cause freemem error, because move is gave c, c1 address freemem again, after error,
2, the following code can modify the content of the pchar:
 
Procedure TForm2. Button10Click (Sender: TObject);
Var
C, c1: PChar;
The begin
GetMem (c, 5);
C1:=c;
C1 ^ :='1';
Inc (c1);
C1 ^ :='3';
Inc (c1);
C1 ^ :='5';

ShowMessage (c);
FreeMem (c);
end;

Pchar actually can be understood as ^ char, pointer to the characters (anyway pointer is the same, is a saved address integer, no matter what to type, type is for the convenience of coding and the concept of out - I understand), getmem give pchar allocates memory, is actually gave pchar an address, and assign a continuous memory space, pchar itself is also the address of an integer, if inc (c), can lead to the c point to the original address of a memory address, actually also can write, but in the end to release the memory, will be an error, because c address is not the original distribution, release the release into the other's memory, so replace c with c1 do operation, move the cursor,

CodePudding user response:

 procedure TForm1. Btn1Click (Sender: TObject); 
Var
C, c1: PChar;
The begin
GetMem (c, 5);
//FillChar (c ^, # 5, 0);
C1:='11.2';
Move (c1 ^, c ^ 4);
C [4] :=# 0;
ShowMessage (c);//11.2
C [0] :='2';
C [3] :='5';
ShowMessage (c);//21.5
FreeMem (c);
end;
  • Related