String assignment behavior

From: James Jones (James_at_jones.com.NOT)
Date: 08/28/04


Date: Sat, 28 Aug 2004 11:34:07 -0500

Hi all,

I've come across a situation that puzzles me quite a bit. Here is how to
reproduce it in Delphi 7, build 8.1:

Start a new project and put this declaration in a form's public section:

String1: string;

Create a button. In it's onclick handler put the following:

Var
  String2: string;
  p1,p2: pchar;

begin

  // set the string
  String1 := 'James' + #9 + 'Jones';

  // this should COPY string1 to string2, right?
  String2 := String1;

  // get a pchar from String2
  P1 := pchar(String2);

  // find the tab character
  P2 := strscan(P1,#9);

  // replace the tab with zero
  P2^ := #0;

The strange behavior I'm noticing is that the P2^ := #0; assignment
changes both String2 AND String1. How can that be?

A fix for the above code would be to replace the String2 := String1
assignment with:

String2 := DupeString ( String1, 1 );

This fixes the behavior I noted.

Is it possible that somehow String1 is passed by reference insteand than
by value? If so, my (object) pascal understanding is pretty deficient despite
the fact that I've been at it since Delphi 1 and college (pascal)!

If any of you guys can explain some of this to me I'd be most appreciative.

Thanks,

James

PS: Strange behavior #2:

Place the String1: String; definition in the Var section of the button onclick
handler and the P2^ := #0; assign will cause an error. Anyone?


Quantcast