rocedure TForm1.OpenClick(Sender: TObject);
var
FileHandle:Integer;
pHead:FileHeadInfo;
pChInfo:pChanInfo;
pData:pCurveData;arr:array of ChanInfo;
begin
if(OpenDialog1.Execute) then
FileHandle:=FileOpen(OpenDialog1.FileName,fmOpenRead);
if (FileHandle>0) then
begin
New(pHead);
FileRead(FileHandle,pHead^,sizeof(FileHeadInfo));
New(pChInfo);
SetLength(arr,pHead^.nChannels);
FileRead(FileHandle,pChInfo^,pHead.nChannels*sizeof(ChanInfo)); copyMemory(@arr,pChInfo,pHead.nChannels*sizeof(ChanInfo));
ShowMessage(arr[0].ChName);
end;
Dispose(pHead);
dispose(pChInfo);
arr:=nil;
FileClose(FileHandle);
end;
var
FileHandle:Integer;
pHead:FileHeadInfo;
pChInfo:pChanInfo;
pData:pCurveData;arr:array of ChanInfo;
begin
if(OpenDialog1.Execute) then
FileHandle:=FileOpen(OpenDialog1.FileName,fmOpenRead);
if (FileHandle>0) then
begin
New(pHead);
FileRead(FileHandle,pHead^,sizeof(FileHeadInfo));
New(pChInfo);
SetLength(arr,pHead^.nChannels);
FileRead(FileHandle,pChInfo^,pHead.nChannels*sizeof(ChanInfo)); copyMemory(@arr,pChInfo,pHead.nChannels*sizeof(ChanInfo));
ShowMessage(arr[0].ChName);
end;
Dispose(pHead);
dispose(pChInfo);
arr:=nil;
FileClose(FileHandle);
end;
pChInfo的指针虽然New创建了,但大小象是未分配,
FileRead(FileHandle,pChInfo^,pHead.nChannels*sizeof(ChanInfo));好象都会有错。注意arr和pChInfo在指针创建时最好成绩都预先分配好大小。
试试
copyMemory(@arr[0],pChInfo,pHead.nChannels*sizeof(ChanInfo));
copyMemory(@arr,pChInfo,pHead.nChannels*sizeof(ChanInfo));
1、pHead声明为FileHeadInfo,不用再用New分配内存,除非FileHeadInfo声明的是指针类型,则;
FileRead(FileHandle,pHead^,sizeof(FileHeadInfo));有问题:sizeof(FileHeadInfo)返回的是指针长度,而不是类型的长度
2、如果1推断是正确的,当然FileRead(FileHandle,pHead^,sizeof(FileHeadInfo));中pHead^引用错误;
3、FileRead(FileHandle,pChInfo^,pHead.nChannels*sizeof(ChanInfo));中,pChInfo只分配了一块pChanInfo内存,如何存储pHead.nChannels块数据???
4、至于后面的copyMemory理所当然Copy的不是想要的数据了。
5、一点建议:在一些分配了内存和文件读写的代码里面,最好使用try...finally..end结构,保证打开的文件最终能关闭,分配的内存最终会释放