指针问题(100分)

  • 主题发起人 主题发起人 panwen
  • 开始时间 开始时间
P

panwen

Unregistered / Unconfirmed
GUEST, unregistred user!
我定义了一个记录类型的数据,然后用一个指针指向它,但是通过指针读取数据的时候会出错,提示“Project Project1.exe raised exception class EAccessViolation with message "Access Violation at address 0040368A in Module 'Project1.exe'.Read address 0013FFDA".Process stopped”,大家帮忙看看怎么回事啊
-------------------------------------------------------------------------------
unit Unit11;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

TCoinsRec = record
quarters,
pennies :word;
end;
PCoinsRec = ^TCoinsRec;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
CoinsRec : PCoinsRec;
begin
With CoinsRec^ do
begin
quarters := 10;
pennies := 20;
end;

With CoinsRec^ do
Form1.Edit1.Text := InttoStr(quarters);

Dispose(CoinsRec);
end;
end.

------------------------------------------------------------------------------
 
你还没有为指针分配内存呢
 
new(CoinsRec);
With CoinsRec^ do
begin
quarters := 10;
pennies := 20;
end;
 
var
CoinsRec : PCoinsRec;
begin
New(CoinsRec)
//!!!!!!!!!!!
With CoinsRec^ do
begin
quarters := 10;
pennies := 20;
end;
With CoinsRec^ do
Form1.Edit1.Text := InttoStr(quarters);
Dispose(CoinsRec);
end;
指针只是个数字标识,你得给它分配空间,它指向的内容才可访问
 
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

TCoinsRec = record
quarters,
pennies :word;
end;
PCoinsRec = ^TCoinsRec;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
CoinsRec : PCoinsRec;
begin
GetMem(CoinsRec,Sizeof(TCoinsRec));
try
with CoinsRec^ do
begin
quarters := 10;
pennies := 20;
end;
With CoinsRec^ do
Form1.Edit1.Text := InttoStr(quarters);
finally
FreeMem(CoinsRec);
end;
end;

end.

你这样写试试,我试过了,可以运行通过
 
hehe,收到
 
后退
顶部