-2

试图编写简单的客户端和服务器通过TMemoryStream. 当我在客户端按下按钮时,btnTestClick它会出现错误 Access violation at address 005D5581 in module 'Client.exe'. Write of adress 00000000。我做错了什么?

顺便说一句,客户端服务器连接工作正常我瘦 cuzIdTCPClient1Connected函数正在编写'Client Connected!'

客户端代码

procedure TForm1.btnTestClick(Sender: TObject);
var
  msRecInfo: TMemoryStream;
  arrOf: array of Integer; i:integer;
begin
  for i := 0 to 10 do
    arrOf[i]:=random(100);

  msRecInfo:= TMemoryStream.Create;

  try
    msRecInfo.Write(arrOf, SizeOf(arrOf));
    idTCPClient1.IOHandler.Write(msRecInfo);
  finally
     msRecInfo.Free;
  end;

end;

end

服务器代码

procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
   msRecInfo: TMemoryStream;
  arrOf: array of Integer; i:integer;
begin
  msRecInfo:= TMemoryStream.Create;
  try
    AContext.Connection.IOHandler.ReadStream(msRecInfo, -1, False);

    msRecInfo.Position := 0;
    msRecInfo.Read(arrof, SizeOf(arrof));
  finally
    memo1.Lines.Add(IntToStr(arrOf[1]));
    msRecInfo.Free;
  end;
  //AContext.Connection.IOHandler.ReadStream(msRecInfo, SizeOf(arrOf));
  //msRecInfo.Read(arrOf, sizeOf(arrOf));
end;
4

1 回答 1

5

You start writing into a dynamic array before you've allocated any elements for it. Dynamic arrays do not automatically grow like you might be used to from some other languages. You need to set their lengths first.

If you haven't set the length of a dynamic array, then it will just be a null pointer, which explains why you get an access violation at address 0.

Change your btnTestClick method like so:

var
  msRecInfo: TMemoryStream;
  arrOf: array of Integer;
  i: integer;
begin
  SetLength(arrOf, 11);
  for i := 0 to 10 do
    arrOf[i] := Random(100);
于 2012-11-21T19:50:04.343 回答