在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),一定会出现空指针错误。
应该将初始化指针放到循环外面。
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),一定会出现空指针错误。
应该将初始化指针放到循环外面。
测试代码如下:
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;