Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to change the Address of a String to equal the addr of another 1

Status
Not open for further replies.

GMcConville

Programmer
Feb 8, 2006
6
NZ
I have been using Delphi for a few years now and one thing I have never been able to do is create a string which is actually part of another string

EG

String1 := 'This is my program';
SetLength(String2, 2);
Addr(String2) := Addr(String1 + 5);
Memo1.Lines.Add(String2);

So therefor String2 equals 'is' from String1. Not a copy of it but directly from that String, so if String1 changes then String2 will always equal the 5th and 6th Character of String1. Any ideas anyone?

Thanks
Grant
 
This is not a possibility due to the internal format of the string variables.

The string variable is really a record that has a length variable at the head of it, and then the determine number of characters. This length variable is what you are setting when you use "SetLength".

Now, the address of the string variable would be the beginning of this length variable.

It is possible however to do this, if string2 were defined as a typed pointer to an array of characters. However, it seems as since strings are dynamically allocated and destroyed, that you would have to establish the reference every time:

Code:
program test1;
  type
    artype = array[1..2] of char;
    arptr = ^artype;
  var
    string1: ShortString;
    string2: arptr;
  begin
    string1 := 'This is my program.';
    string2 := @string1[6];
    writeln(string1);
    writeln(string2^);

    string1 := 'This was my program.';
    string2 := @string1[6];
    writeln(string1);
    writeln(string2^);
  end.
 
Furthermore, the string's data space (memory used for the chars) can change at any time.

Say you have the string S = '1'; changing the value to S := '1234567890' can make the memory manager to free the original memory chunk and allocate another, best fitted for the new length.

You can crack the string control record (it is documented somewhere in the Object Pascal PDF) to get the data space pointer, but you are not assured the pointer will stay unchanged along the run.

I have not idea why you need a trick like the one you are trying to put up, but I think you are using the wrong data structure for it.

Better use a fixed buffer, to which you can pointer pointers to your heart content :). Keep you buffer zero-end marked and you can typecast it to a PChar to work it like a string.

buho (A).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top