我的循环链接怎么不对?

chons 2001-10-18 12:10:37
var
p,current,head,tail:pType;
for i:=1 to 6 do
begin
new(p);
current:=nil;
head:=nil;
tail:=nil;
p^.data:=i;
p^.next:=nil;
if i=1 then head=p
else current^.next:=p;
current:=p;
if i=6 then
begin
tail:=p;
current^.next:=head;
end;
end;
结果在那一步就出现了运行错误,编译是没有错误的。这个方法在VC里是完全正确的。在
Delphi里怎么会错误呢。
哪位知道告诉我啊。
刚学Delphi指针啊。
...全文
67 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
gzmhero 2001-10-19
  • 打赏
  • 举报
回复
还有什么错误呢,我试过,代码是没有问题的。
测试代码如下:
procedure TForm1.Button1Click(Sender: TObject);
type
pType=^MyType;
MyType=record
data:integer;
next:pType;
end;
var
p,current,head,tail:pType;
i:integer;
begin
current:=nil;
head:=nil;
tail:=nil;
for i:=1 to 6 do
begin
new(p);
p^.data:=i;
p^.next:=nil;
if i=1 then
head:=p
else
current^.next:=p;
current:=p;
if i=6 then
begin
tail:=p;
current^.next:=head;
end;
end;
end;
gzmhero 2001-10-18
  • 打赏
  • 举报
回复
在VC中美错误,不会吧,你的代码有错误。

current:=nil; ...........................(1)
head:=nil;
tail:=nil;
p^.data:=i;
p^.next:=nil;
if i=1 then .................................(2)
head=p
else
current^.next:=p; .........................(3)
current:=p;

在上面的一段代码中,当i=2时,即循环第二轮,此时执行了current:=nil;(1)处,指针
current是空的,再执行(2)时此时,i=2,会执行(3),一定会出现空指针错误。
应该将初始化指针放到循环外面。
chons 2001-10-18
  • 打赏
  • 举报
回复
有道理。我把初始化指针放到外面。还是有错误。真的。那是为什么呢?

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧