Can multiple string variables refer to the same data?

According to information on the Internet, I found that the following two variables point to the same place in memory.

Can someone suggest a code example to demonstrate that this is actually true (for example, by changing one of the letters in the first variable and seeing 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; 
+4
source share
5 answers
 var a, b: string; begin a := 'Test'; a := a + '!'; // added after Rob comment below, // makes sure a points to an allocation on the heap b := a; PChar(b)[3] := 'T'; ShowMessage(a); //--> TesT! end; 
+1
source
 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 indicate the same data.

note 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.

Also note 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 in some place in memory ( @a ) there is data address a , and somewhere else ( @b ) is data address b . The first example shows that these two places in memory contain the same address, that is, a and b contain the same data.

+8
source

Normally, Delphi uses copy-on-write semantics for strings, so you need a hacker to do the trick, for example:

 procedure TForm13.Button1Click(Sender: TObject); const Test: string = '12345'; var S1, S2: string; P: PChar; begin SetString(S1, PChar(Test), 5); // we need to copy '12345' string from readonly memory to heap S2:= S1; // Now both S1 and S2 points to the same memory P:= Pointer(S1); P^:= 'A'; ShowMessage(S2); // 'A2345' end; 
+3
source

Your question is not very clear to me. If you do:

 begin a := 'Test'; b := a; a := a+'HH'; showmessage (a); showmessage (b); end; 

I think you will see this ...

0
source

OK could be more clear with this code

 procedure TForm1.FormCreate(Sender: TObject); var a, b , s : string; p : pointer; begin a := 'Test'; b := a; // we see the 2 diff. var pointing on the same adress s := Format('%p -> %p / %p -> %p', [@pointer(a),pointer(a),@pointer(b),pointer(b)] ); ShowMessage( 'first : '+s); // we see the 2 diff. var pointing on different adresses a := 'Test2'; s := Format('%p -> %p / %p -> %p', [@pointer(a),pointer(a),@pointer(b),pointer(b)] ); ShowMessage( 'second : '+s); end; 
0
source

Source: https://habr.com/ru/post/1343947/


All Articles