Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2006.06.25;
Скачать: CL | DM;

Вниз

Как хранится переменная типа String в памяти.   Найти похожие ветки 

 
AlexanderMS ©   (2006-06-07 16:57) [0]

Что-то непонятно, в Pascal строковая переменная содержит длину строки в байте под №0. А в Delphi строки могут быть длиннее 255 символов, и, как следствие, 1 байт не подойдёт. Прочитал в справке, что тип string воспринимается как LongString, если не использовать соответствующую директиву. Вот PChar всё ясно - определяется по #0. Но как хранятся строки типа LongString, и где указана длина?


 
McSimm ©   (2006-06-07 17:07) [1]

Длина строки хранится в двойном слове (4 байта) перед непосредственно строкой.
Перед длиной имеется также и другая информация, тоже по 4 байта - счетчик ссылок и объем распределенной памяти.


 
Ega23 ©   (2006-06-07 17:07) [2]

PChar и HugeString - почти одно и то же. Окончанием также служит #0


 
AlexanderMS ©   (2006-06-07 17:11) [3]

Спасибо.

HugeString - то же, что и LongString?


 
McSimm ©   (2006-06-07 17:12) [4]


> McSimm ©   (07.06.06 17:07) [1]

Добавлю, что знать это надо не более чем для понимания механизма работы со строками. Для самой работы со строками эта информация не нужна и использовать эти области программисту вряд ли есть смысл


 
McSimm ©   (2006-06-07 17:14) [5]

Окончание #0 в LongString тоже есть, но используется просто для удобства.


 
Ega23 ©   (2006-06-07 17:16) [6]


A string represents a sequence of characters. Object Pascal supports the following predefined string types.

Type Maximum length Memory required Used for
ShortString 255 characters 2 to 256 bytes backward compatibility
AnsiString ~2^31 characters 4 bytes to 2GB 8-bit (ANSI) characters
WideString ~2^30 characters 4 bytes to 2GB Unicode characters;
COM servers and interfaces
AnsiString, sometimes called the long string, is the preferred type for most purposes.
String types can be mixed in assignments and expressions; the compiler automatically performs required conversions. But strings passed by reference to a function or procedure (as var and out parameters) must be of the appropriate type. Strings can be explicitly cast to a different string type (see Typecasts).
The reserved word string functions like a generic type identifier. For example,

var S: string;

creates a variable S that holds a string. In the default {$H+} state, the compiler interprets string (when it appears without a bracketed number after it) as AnsiString. Use the {$H–} directive to turn string into ShortString.
The standard function Length returns the number of characters in a string. The SetLength procedure adjusts the length of a string.
Comparison of strings is defined by the ordering of the characters in corresponding positions. Between strings of unequal length, each character in the longer string without a corresponding character in the shorter string takes on a greater-than value. For example, “AB” is greater than “A”; that is, "AB" > "A" returns True. Zero-length strings hold the lowest values.

You can index a string variable just as you would an array. If S is a string variable and i an integer expression, S[i] represents the ith character—or, strictly speaking, the ith byte—in S. For a ShortString or AnsiString, S[i] is of type AnsiChar; for a WideString, S[i] is of type WideChar. The statement MyString[2] := "A"; assigns the value A to the second character of MyString. The following code uses the standard UpCase function to convert MyString to uppercase.

var I: Integer;

begin
 I := Length(MyString);
 while I > 0 do
 begin
   MyString[I] := UpCase(MyString[I]);
   I := I - 1;
 end;
end;

Be careful indexing strings in this way, since overwriting the end of a string can cause access violations. Also, avoid passing long-string indexes as var parameters, because this results in inefficient code.
You can assign the value of a string constant—or any other expression that returns a string—to a variable. The length of the string changes dynamically when the assignment is made. Examples:

MyString := "Hello world!";

MyString := "Hello " + "world";
MyString := MyString + "!";
MyString := " ";               { space }
MyString := "";                { empty string }


 
sniknik ©   (2006-06-07 17:40) [7]

> Окончание #0 в LongString тоже есть, но используется просто для удобства.
+
так приведение типа к PChar например (нужно часто) просто дает адрес начала строки, и т.к. в конце уже есть "лишний" #0 то совместимость сразу полная. стоит 1 лишнего символа на каждую строку... (не было бы, пришлось бы память перевыделять копировать с #0 из оригинала, напряжно получится)



Страницы: 1 вся ветка

Текущий архив: 2006.06.25;
Скачать: CL | DM;

Наверх




Память: 0.49 MB
Время: 0.043 c
2-1149614577
Revan
2006-06-06 21:22
2006.06.25
Как поменять иконку exe файла?


15-1148824131
[wl]
2006-05-28 17:48
2006.06.25
Freecell, он же "Солитер", стандартная игра к Windows 2000/XP


1-1147975944
anton773
2006-05-18 22:12
2006.06.25
Преобразование типов


6-1132257651
Иван12345
2005-11-17 23:00
2006.06.25
Перехват данных из входящего трафика


3-1145982888
DDDiM
2006-04-25 20:34
2006.06.25
MYSQL И DELPHI