Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple string variables really refer to the same data?

According to the information in the internet I found out that two following variables point to the same place in memory.

Could anyone propose a code example to demonstrate that in fact it is true (e.g. by changing one of the letter in the 1st variable and see that this change is visible from the second variable)?

procedure TForm1.Button1Click(Sender: TObject);
var
  a, b: String;
begin
  a := 'Test';
  b := a;

  showmessage (a);
  showmessage (b);
end;
like image 917
Paul Avatar asked Dec 17 '22 16:12

Paul


1 Answers

procedure TForm4.FormCreate(Sender: TObject);
var
  a, b: string;
begin
  a := 'Test';
  b := a;
  ShowMessage(BoolToStr(pointer(a) = pointer(b), true));
end;

The result is True, so yes, a and b point to the same data.

Notice, however, that

procedure TForm4.FormCreate(Sender: TObject);
var
  a, b: string;
begin
  a := 'Test';
  b := a;
  b := 'Test2';
  ShowMessage(BoolToStr(pointer(a) = pointer(b), true));
end;

displays False, as it should be.

In addition, notice that

procedure TForm4.FormCreate(Sender: TObject);
var
  a, b: string;
begin
  a := 'Test';
  b := a;
  ShowMessage(BoolToStr(@a = @b, true));
end;

also displays False, because a and b are different string (pointer) variables, so at some place in memory (@a) is the address of the data of a, and somewhere else (@b) is the address of the data of b. The first example shows that these two places in memory contain the same address, that is, that a and b contain the same data.

like image 125
Andreas Rejbrand Avatar answered Dec 28 '22 22:12

Andreas Rejbrand