Delphi: 如何使用两个for循环将数据输入到记录数组中?
Delphi: How to Input data into an record array using two for loops?
我在将数据输入记录数组时遇到问题,一旦我超过第 5 个输入,它就会崩溃,我不明白为什么。如图所示,我在 for
循环内有一个 for 循环,是否正在输入数据取决于 for
循环不起作用
uses
System.SysUtils;
type
TPerson = record
Name: string;
Friends: array of TPerson;
end;
var
Paul: TPerson;
A,B:Integer;
begin
SetLength(Paul.Friends, 5);
SetLength(Paul.Friends[0].Friends, 5);
SetLength(Paul.Friends[1].Friends, 5);
for A := 1 to 5 do
begin
for B := 1 to 5 do
begin
writeln('Input data');
readln(Paul.Friends[A].Friends[B].Name);
end;
end;
end.
崩溃只是说 windows 检测到问题并且程序冻结。
您发布的代码有几个问题。
- 你分配的数组有误
- 访问数组时你的循环不正确
- 动态数组以索引 0 开头,因此超出了数组长度
这是一个按照您的意图从数组中正确初始化(和读回)的示例。我将把第一个循环转换为从控制台读取输入的任务留给您。它是按照 Delphi XE7 控制台应用程序中编写的那样进行编译和测试的。
program Project2;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TPerson = record
Name: string;
Friends: array of TPerson;
end;
var
Paul: TPerson;
A,B:Integer;
begin
Paul.Name := 'Paul';
// Initialize Paul's Friends
SetLength(Paul.Friends, 5);
// Initialize each of Paul's friends Friends
for A := 0 to 4 do
SetLength(Paul.Friends[A].Friends, 5);
for A := 0 to 4 do
begin
Paul.Friends[A].Name := Format('Friend %d', [A]);
for B := 0 to 4 do
Paul.Friends[A].Friends[B].Name := Format('Friend %d of friend %d', [B, A]);
end;
// Write out what we did with the code above
for A := 0 to 4 do
begin
WriteLn(Paul.Friends[A].Name);
for B := 0 to 4 do
WriteLn(Paul.Friends[A].Friends[B].Name);
end;
ReadLn;
end.
我在将数据输入记录数组时遇到问题,一旦我超过第 5 个输入,它就会崩溃,我不明白为什么。如图所示,我在 for
循环内有一个 for 循环,是否正在输入数据取决于 for
循环不起作用
uses
System.SysUtils;
type
TPerson = record
Name: string;
Friends: array of TPerson;
end;
var
Paul: TPerson;
A,B:Integer;
begin
SetLength(Paul.Friends, 5);
SetLength(Paul.Friends[0].Friends, 5);
SetLength(Paul.Friends[1].Friends, 5);
for A := 1 to 5 do
begin
for B := 1 to 5 do
begin
writeln('Input data');
readln(Paul.Friends[A].Friends[B].Name);
end;
end;
end.
崩溃只是说 windows 检测到问题并且程序冻结。
您发布的代码有几个问题。
- 你分配的数组有误
- 访问数组时你的循环不正确
- 动态数组以索引 0 开头,因此超出了数组长度
这是一个按照您的意图从数组中正确初始化(和读回)的示例。我将把第一个循环转换为从控制台读取输入的任务留给您。它是按照 Delphi XE7 控制台应用程序中编写的那样进行编译和测试的。
program Project2;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TPerson = record
Name: string;
Friends: array of TPerson;
end;
var
Paul: TPerson;
A,B:Integer;
begin
Paul.Name := 'Paul';
// Initialize Paul's Friends
SetLength(Paul.Friends, 5);
// Initialize each of Paul's friends Friends
for A := 0 to 4 do
SetLength(Paul.Friends[A].Friends, 5);
for A := 0 to 4 do
begin
Paul.Friends[A].Name := Format('Friend %d', [A]);
for B := 0 to 4 do
Paul.Friends[A].Friends[B].Name := Format('Friend %d of friend %d', [B, A]);
end;
// Write out what we did with the code above
for A := 0 to 4 do
begin
WriteLn(Paul.Friends[A].Name);
for B := 0 to 4 do
WriteLn(Paul.Friends[A].Friends[B].Name);
end;
ReadLn;
end.