请考虑以下代码:
procedure Test;
var
MyPCharArray: array of PChar;
begin
SetLength(MyPCharArray, 3);
GetMem(MyPCharArray[0], 5);
GetMem(MyPCharArray[1], 5);
GetMem(MyPCharArray[2], 5);
StrCopy(MyPCharArray[0], 'test');
StrCopy(MyPCharArray[1], 'abcd');
StrCopy(MyPCharArray[2], '1234');
// Are these necessary?
FreeMem(MyPCharArray[0], 5);
FreeMem(MyPCharArray[1], 5);
FreeMem(MyPCharArray[2], 5);
end;
是否应手动释放已分配的元素,否则编译器会在MyPCharArray
超出范围时自动释放数组元素?
答案 0 :(得分:5)
确实,您对GetMem的每次调用都必须与对FreeMem的调用相匹配。
我不知道为什么你有这个阵列。它不是我期望在纯Pascal代码中看到的类型。所以我的猜测是你将PChar数组传递给一些外部库。在这种情况下,我将声明一个字符串数组以及PChar数组。然后在字符串数组的相应元素上使用PChar(...)创建每个PChar元素。然后你可以避免使用StrCopy,GetMem和FreeMem。
procedure CallLib(const str: array of string);
var
i: Integer;
parr: array of PChar;
begin
SetLength(parr, Length(str));
for i := 0 to high(parr) do
parr[i] := PChar(str[i]);
// call library now
end;